Home Backend Development C#.Net Tutorial Sample code sharing of 7 methods for C# to obtain local IP collection and sorting

Sample code sharing of 7 methods for C# to obtain local IP collection and sorting

May 11, 2018 pm 01:52 PM

C#Get sample code sharing for 7 methods of collecting and sorting local IP

 1 private void GetIP()  
 2 {  
 3     string hostName = Dns.GetHostName();//本机名   
 4     //System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//会警告GetHostByName()已过期,我运行时且只返回了一个IPv4的地址    
 5     System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//会返回所有地址,包括IPv4和IPv6    
 6     foreach (IPAddress ip in addressList)  
 7     {  
 8         listBox1.Items.Add(ip.ToString());  
 9     }  
10 }
Copy after login

② Use IPHostEntry to obtain the local area network address

1         static string GetLocalIp()  
2         {  
3             string hostname = Dns.GetHostName();//得到本机名   
4             //IPHostEntry localhost = Dns.GetHostByName(hostname);//方法已过期,只得到IPv4的地址   
5 <SPAN style="WHITE-SPACE: pre"> </SPAN>    IPHostEntry localhost = Dns.GetHostEntry(hostname);  
6             IPAddress localaddr = localhost.AddressList[0];  
7             return localaddr.ToString();  
8         }
Copy after login

③ Obtain the local network ip address

method by sending webrequests to some websites that provide IP query, and then analyze Returned data stream

 1        string strUrl = "提供IP查询的网站的链接";  
 2        Uri uri = new Uri(strUrl);  
 3        WebRequest webreq = WebRequest.Create(uri);  
 4        Stream s = webreq .GetResponse().GetResponseStream();  
 5        StreamReader sr = new StreamReader(s, Encoding.Default);  
 6        string all = sr.ReadToEnd();   
 7        int i = all.IndexOf("[") + 1;  
 8        //分析字符串得到IP    9        return ip;  
10        /* 11         我用的是http://www.php.cn/    
12         (这种链接很容易找的,百度“IP”得到一些网站,分析一下网站的链接就能得到) 
13         返回的数据是:  
14         <p class="well"><p>当前 IP:<code>0.0.0.0</code> 来自:XX省XX市 电信</p><p>GeoIP: Beijing, China</p></p>  
15         解析这段就行  
16       */
Copy after login

④//Due to the use of ManagementClass, ManagementObjectCollection; reference System.Management.# must be added ##dlland using System.Management;

 1 private void GetIP2()  
 2         {  
 3             string stringMAC = "";  
 4             string stringIP = "";  
 5             ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");  
 6             ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();  
 7             foreach(ManagementObject managementObject in managementObjectCollection)  
 8             {  
 9                 if ((bool)managementObject["IPEnabled"] == true)  
10                 {  
11                     stringMAC += managementObject["MACAddress"].ToString();  
12                     string[] IPAddresses = (string[])managementObject["IPAddress"];  
13                     if (IPAddresses.Length > 0)  
14                     {  
15                         stringIP = IPAddresses[0];   
16                     }  
17                 }  
18             }  
19             txtMAC.Text = stringMAC.ToString();  
20             txtIP.Text = stringIP.ToString();  
21         }
Copy after login

⑤Calling the Web service provided by a website to query the IP address

It took a long time, but I didn’t learn how to call the Web Service. According to the search The page I arrived at is not working, so I gave up first... After all, I haven't come into contact with WebService yet. It will be easy to get WebService another day (leave it for future improvement)

⑥ Get the ipconfig in CMD Get the result of the command to get the IP

 1    private void GetIP6()  
 2    {  
 3        Process cmd = new Process();  
 4        cmd.StartInfo.FileName = "ipconfig.exe";//设置程序名    5        cmd.StartInfo.Arguments = "/all";  //参数   
 6 //重定向标准输出    7        cmd.StartInfo.RedirectStandardOutput = true;  
 8        cmd.StartInfo.RedirectStandardInput = true;  
 9        cmd.StartInfo.UseShellExecute = false;  
10        cmd.StartInfo.CreateNoWindow = true;//不显示窗口(控制台程序是黑屏)   
11 //cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//暂时不明白什么意思   12        /* 13 收集一下 有备无患 
14        关于:ProcessWindowStyle.Hidden隐藏后如何再显示? 
15        hwndWin32Host = Win32Native.FindWindow(null, win32Exinfo.windowsName); 
16        Win32Native.ShowWindow(hwndWin32Host, 1);     //先FindWindow找到窗口后再ShowWindow 
17        */  18        cmd.Start();  
19        string info = cmd.StandardOutput.ReadToEnd();  
20        cmd.WaitForExit();  
21        cmd.Close();  
22        textBox1.AppendText(info);  
23    }
Copy after login

⑦NetworkInformation

 1 private void GetIP5()  
 2        {  
 3     //需要的命名空间   
 4            //using System.Net.NetworkInformation;   
 5            //using System.Net.Sockets;    6            string str = "";  
 7            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();  
 8            int i = 0;  
 9            foreach (NetworkInterface adapter in adapters)  
10            {  
11   12                IPInterfaceProperties adapterProperties = adapter.GetIPProperties();  
13                UnicastIPAddressInformationCollection allAddress =  
14 adapterProperties.UnicastAddresses;  
15                if (allAddress.Count > 0)  
16                {  
17                    str += "interface   " + i + "description:\n\t " + adapter.Description + "\n ";  
18                    i++;  
19                    foreach (UnicastIPAddressInformation addr in allAddress)  
20                    {  
21                        if (addr.Address.AddressFamily == AddressFamily.InterNetworkV6)  
22                        {  
23                            ipListComb.Items.Add(addr.Address);  
24                        }  
25                        if (addr.Address.AddressFamily == AddressFamily.InterNetwork)  
26                        {  
27                            comboBox1.Items.Add(addr.Address);  
28                        }  
29   30                    }  
31                }  
32            }  
33            MessageBox.Show(str);  
34        }
Copy after login

The above is the detailed content of Sample code sharing of 7 methods for C# to obtain local IP collection and sorting. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles