首页 > 代码库 > C#获取本机内网外网IP
C#获取本机内网外网IP
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
C#获取本机内网外网IP
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。