using System.Net; # region 獲取內、外網Ip /// <summary> /// 獲取本地ip地址,優先取內網ip /// </summary> public static String GetLocalIp() { String[] Ips = GetLocalIpAddress(); foreach (String ip in Ips) if (ip.StartsWith("10.80.")) return ip; foreach (String ip in Ips) if (ip.Contains(".")) return ip; return "127.0.0.1"; } /// <summary> /// 獲取本地ip地址。多個ip /// </summary> public static String[] GetLocalIpAddress() { string hostName = Dns.GetHostName(); //獲取主機名稱 IPAddress[] addresses = Dns.GetHostAddresses(hostName); //解析主機IP地址 string[] IP = new string[addresses.Length]; //轉換為字符串形式 for (int i = 0; i < addresses.Length; i++) IP[i] = addresses[i].ToString(); return IP; } /// <summary> /// 獲取外網ip地址 /// </summary> public static string GetExtenalIpAddress_0() { string IP = "未獲取到外網ip"; try { //從網址中獲取本機ip數據 System.Net.WebClient client = new System.Net.WebClient(); client.Encoding = System.Text.Encoding.Default; string str = client.DownloadString("http://1111.ip138.com/ic.asp"); client.Dispose(); //提取外網ip數據 [218.104.71.178] int i1 = str.IndexOf("["), i2 = str.IndexOf("]"); IP = str.Substring(i1 + 1, i2 - 1 - i1); } catch (Exception) { } return IP; } /// <summary> /// 獲取外網ip地址 /// </summary> public static string GetExtenalIpAddress() { String url = "http://hijoyusers.joymeng.com:8100/test/getNameByOtherIp"; string IP = "未獲取到外網ip"; try { //從網址中獲取本機ip數據 System.Net.WebClient client = new System.Net.WebClient(); client.Encoding = System.Text.Encoding.Default; string str = client.DownloadString(url); client.Dispose(); if (!str.Equals("")) IP = str; else IP = GetExtenalIpAddress_0(); } catch (Exception) { } return IP; } # endregion