1. 程式人生 > WINDOWS開發 >C#獲取本地IP地址,內網+外網方法

C#獲取本地IP地址,內網+外網方法

 1 #region 獲取內、外網Ip
 2 
 3         /// <summary>
 4         /// 獲取本地ip地址,優先取內網ip
 5         /// </summary>
 6         public static String GetLocalIp()
 7         {
 8             String[] Ips = GetLocalIpAddress();
 9 
10             foreach (String ip in Ips) if (ip.StartsWith("10.80.")) return ip;
11 foreach (String ip in Ips) if (ip.Contains(".")) return ip; 12 13 return "127.0.0.1"; 14 } 15 16 /// <summary> 17 /// 獲取本地ip地址。多個ip 18 /// </summary> 19 public static String[] GetLocalIpAddress() 20 { 21 string hostName = Dns.GetHostName(); //
獲取主機名稱 22 IPAddress[] addresses = Dns.GetHostAddresses(hostName); //解析主機IP地址 23 24 string[] IP = new string[addresses.Length]; //轉換為字串形式 25 for (int i = 0; i < addresses.Length; i++) IP[i] = addresses[i].ToString(); 26 27 return IP; 28
} 29 30 /// <summary> 31 /// 獲取外網ip地址 32 /// </summary> 33 public static string GetExtenalIpAddress_0() 34 { 35 string IP = "未獲取到外網ip"; 36 try 37 { 38 //從網址中獲取本機ip資料 39 System.Net.WebClient client = new System.Net.WebClient(); 40 client.Encoding = System.Text.Encoding.Default; 41 string str = client.DownloadString("http://1111.ip138.com/ic.asp"); 42 client.Dispose(); 43 44 //提取外網ip資料 [218.104.71.178] 45 int i1 = str.IndexOf("["),i2 = str.IndexOf("]"); 46 IP = str.Substring(i1 + 1,i2 - 1 - i1); 47 } 48 catch (Exception) { } 49 50 return IP; 51 } 52 53 /// <summary> 54 /// 獲取外網ip地址 55 /// </summary> 56 public static string GetExtenalIpAddress() 57 { 58 String url = "http://hijoyusers.joymeng.com:8100/test/getNameByOtherIp"; 59 string IP = "未獲取到外網ip"; 60 try 61 { 62 //從網址中獲取本機ip資料 63 System.Net.WebClient client = new System.Net.WebClient(); 64 client.Encoding = System.Text.Encoding.Default; 65 string str = client.DownloadString(url); 66 client.Dispose(); 67 68 if (!str.Equals("")) IP = str; 69 else IP = GetExtenalIpAddress_0(); 70 } 71 catch (Exception) { } 72 73 return IP; 74 } 75 76 #endregion

為了獲取IP 我尋找了很多方法 大部分還是獲得全部IP

//獲取全部IP  
string name = Dns.GetHostName(); IPAddress[] ipadrlist = Dns.GetHostAddresses(name);


//獲取全部IP IPHostEntry myEntry
= Dns.GetHostEntry(Dns.GetHostName()); myEntry.AddressList.FirstOrDefault<IPAddress>(e => e.AddressFamily.ToString().Equals("InterNetwork")).ToString(); /// <summary> /// 獲取本地IP地址資訊 /// </summary> void GetAddressIP() { ///獲取本地的IP地址 string AddressIP = string.Empty; foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (_IPAddress.AddressFamily.ToString() == "InterNetwork") { AddressIP = _IPAddress.ToString(); } } string Text = AddressIP; }