程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#獲取本機IP搜集整理幾種方法

C#獲取本機IP搜集整理幾種方法

編輯:C#入門知識

print?1、//GetHostName  
private void GetIP()   
 {   
     string hostName = Dns.GetHostName();//本機名     
     //System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//會警告GetHostByName()已過期,我運行時且只返回了一個IPv4的地址     
     System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//會返回所有地址,包括IPv4和IPv6     
     foreach (IPAddress ip in addressList)   
     {   
         listBox1.Items.Add(ip.ToString());   
     }   
 } 

1、//GetHostName
private void GetIP() 
 { 
     string hostName = Dns.GetHostName();//本機名  
     //System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//會警告GetHostByName()已過期,我運行時且只返回了一個IPv4的地址  
     System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//會返回所有地址,包括IPv4和IPv6  
     foreach (IPAddress ip in addressList) 
     { 
         listBox1.Items.Add(ip.ToString()); 
     } 
 }
2、使用IPHostEntry獲取本機局域網地址

[csharp]
static string GetLocalIp()   
         {   
             string hostname = Dns.GetHostName();//得到本機名     
             //IPHostEntry localhost = Dns.GetHostByName(hostname);//方法已過期,只得到IPv4的地址     
         IPHostEntry localhost = Dns.GetHostEntry(hostname);   
             IPAddress localaddr = localhost.AddressList[0];   
             return localaddr.ToString();   
         } 

static string GetLocalIp() 
         { 
             string hostname = Dns.GetHostName();//得到本機名  
             //IPHostEntry localhost = Dns.GetHostByName(hostname);//方法已過期,只得到IPv4的地址  
      IPHostEntry localhost = Dns.GetHostEntry(hostname); 
             IPAddress localaddr = localhost.AddressList[0]; 
             return localaddr.ToString(); 
         }
3、獲取本機網絡ip地址

[csharp]
string strUrl = "提供IP查詢的網站的鏈接";   
        Uri uri = new Uri(strUrl);   
        WebRequest webreq = WebRequest.Create(uri);   
        Stream s = webreq .GetResponse().GetResponseStream();   
        StreamReader sr = new StreamReader(s, Encoding.Default);   
        string all = sr.ReadToEnd();    
        int i = all.IndexOf("[") + 1;   
        //分析字符串得到IP     
        return ip;   
        /* 
         我用的是http://www.ip.cn/getip.php?action=getip&ip_url=&from=web    
         (這種鏈接很容易找的,百度“IP”得到一些網站,分析一下網站的鏈接就能得到) 
         返回的數據是:  
         <div class="well"><p>當前 IP:<code>0.0.0.0</code> 來自:XX省XX市 電信</p><p>GeoIP: Beijing, China</p></div>  
         解析這段就行  
       */ 

string strUrl = "提供IP查詢的網站的鏈接"; 
        Uri uri = new Uri(strUrl); 
        WebRequest webreq = WebRequest.Create(uri); 
        Stream s = webreq .GetResponse().GetResponseStream(); 
        StreamReader sr = new StreamReader(s, Encoding.Default); 
        string all = sr.ReadToEnd();  
        int i = all.IndexOf("[") + 1; 
        //分析字符串得到IP  
        return ip; 
        /*
         我用的是http://www.ip.cn/getip.php?action=getip&ip_url=&from=web   
         (這種鏈接很容易找的,百度“IP”得到一些網站,分析一下網站的鏈接就能得到)
         返回的數據是: 
         <div class="well"><p>當前 IP:<code>0.0.0.0</code> 來自:XX省XX市 電信</p><p>GeoIP: Beijing, China</p></div> 
         解析這段就行 
       */
4、//由於用到了ManagementClass、ManagementObjectCollection;必須添加引用System.Management.dll及using System.Management;

 

[csharp] view plaincopyprint?private void GetIP2()   
         {   
             string stringMAC = "";   
             string stringIP = "";   
             ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");   
             ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();   
             foreach(ManagementObject managementObject in managementObjectCollection)   
             {   
                 if ((bool)managementObject["IPEnabled"] == true)   
                 {   
                     stringMAC += managementObject["MACAddress"].ToString();   
                     string[] IPAddresses = (string[])managementObject["IPAddress"];   
                     if (IPAddresses.Length > 0)   
                     {   
                         stringIP = IPAddresses[0];    
                     }   
                 }   
             }   
             txtMAC.Text = stringMAC.ToString();   
             txtIP.Text = stringIP.ToString();   
         } 

private void GetIP2() 
         { 
             string stringMAC = ""; 
             string stringIP = ""; 
             ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); 
             ManagementObjectCollection managementObjectCollection = managementClass.GetInstances(); 
             foreach(ManagementObject managementObject in managementObjectCollection) 
             { 
                 if ((bool)managementObject["IPEnabled"] == true) 
                 { 
                     stringMAC += managementObject["MACAddress"].ToString(); 
                     string[] IPAddresses = (string[])managementObject["IPAddress"]; 
                     if (IPAddresses.Length > 0) 
                     { 
                         stringIP = IPAddresses[0];  
                     } 
                 } 
             } 
             txtMAC.Text = stringMAC.ToString(); 
             txtIP.Text = stringIP.ToString(); 
         }
 

5、通過獲取CMD裡ipconfig命令的結果來得到IP    

 

[csharp]
private void GetIP6()   
    {   
        Process cmd = new Process();   
        cmd.StartInfo.FileName = "ipconfig.exe";//設置程序名     
        cmd.StartInfo.Arguments = "/all";  //參數     
    //重定向標准輸出     
        cmd.StartInfo.RedirectStandardOutput = true;   
        cmd.StartInfo.RedirectStandardInput = true;   
        cmd.StartInfo.UseShellExecute = false;   
        cmd.StartInfo.CreateNoWindow = true;//不顯示窗口(控制台程序是黑屏)     
    //cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//暫時不明白什麼意思     
        /* 
    收集一下 有備無患 
        關於:ProcessWindowStyle.Hidden隱藏後如何再顯示? 
        hwndWin32Host = Win32Native.FindWindow(null, win32Exinfo.windowsName); 
        Win32Native.ShowWindow(hwndWin32Host, 1);     //先FindWindow找到窗口後再ShowWindow 
        */   
        cmd.Start();   
        string info = cmd.StandardOutput.ReadToEnd();   
        cmd.WaitForExit();   
        cmd.Close();   
        textBox1.AppendText(info);   
    } 

private void GetIP6() 
    { 
        Process cmd = new Process(); 
        cmd.StartInfo.FileName = "ipconfig.exe";//設置程序名  
        cmd.StartInfo.Arguments = "/all";  //參數  
  //重定向標准輸出  
        cmd.StartInfo.RedirectStandardOutput = true; 
        cmd.StartInfo.RedirectStandardInput = true; 
        cmd.StartInfo.UseShellExecute = false; 
        cmd.StartInfo.CreateNoWindow = true;//不顯示窗口(控制台程序是黑屏)  
 //cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//暫時不明白什麼意思  
        /*
  收集一下 有備無患
        關於:ProcessWindowStyle.Hidden隱藏後如何再顯示?
        hwndWin32Host = Win32Native.FindWindow(null, win32Exinfo.windowsName);
        Win32Native.ShowWindow(hwndWin32Host, 1);     //先FindWindow找到窗口後再ShowWindow
        */ 
        cmd.Start(); 
        string info = cmd.StandardOutput.ReadToEnd(); 
        cmd.WaitForExit(); 
        cmd.Close(); 
        textBox1.AppendText(info); 
    }
 

6、NetworkInformation

 

[csharp]
private void GetIP5()   
        {   
     //需要的命名空間     
            //using System.Net.NetworkInformation;     
            //using System.Net.Sockets;     
            string str = "";   
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();   
            int i = 0;   
            foreach (NetworkInterface adapter in adapters)   
            {   
    
                IPInterfaceProperties adapterProperties = adapter.GetIPProperties();   
                UnicastIPAddressInformationCollection allAddress =   
                                                                                        adapterProperties.UnicastAddresses;   
                if (allAddress.Count > 0)   
                {   
                    str += "interface   " + i + "description:\n\t " + adapter.Description + "\n ";   
                    i++;   
                    foreach (UnicastIPAddressInformation addr in allAddress)   
                    {   
                        if (addr.Address.AddressFamily == AddressFamily.InterNetworkV6)   
                        {   
                            ipListComb.Items.Add(addr.Address);   
                        }   
                        if (addr.Address.AddressFamily == AddressFamily.InterNetwork)   
                        {   
                            comboBox1.Items.Add(addr.Address);   
                        }   
    
                    }   
                }   
            }   
            MessageBox.Show(str);   
        } 

private void GetIP5() 
        { 
     //需要的命名空間  
            //using System.Net.NetworkInformation;  
            //using System.Net.Sockets;  
            string str = ""; 
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); 
            int i = 0; 
            foreach (NetworkInterface adapter in adapters) 
            { 
  
                IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); 
                UnicastIPAddressInformationCollection allAddress = 
                                                                                        adapterProperties.UnicastAddresses; 
                if (allAddress.Count > 0) 
                { 
                    str += "interface   " + i + "description:\n\t " + adapter.Description + "\n "; 
                    i++; 
                    foreach (UnicastIPAddressInformation addr in allAddress) 
                    { 
                        if (addr.Address.AddressFamily == AddressFamily.InterNetworkV6) 
                        { 
                            ipListComb.Items.Add(addr.Address); 
                        } 
                        if (addr.Address.AddressFamily == AddressFamily.InterNetwork) 
                        { 
                            comboBox1.Items.Add(addr.Address); 
                        } 
  
                    } 
                } 
            } 
            MessageBox.Show(str); 
        }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved