C#获取本机局域网IP和公网IP

1.获取本机局域网IP

public static string GetInternalIp()
        {
            IPHostEntry myEntry = Dns.GetHostEntry(Dns.GetHostName());
           return myEntry.AddressList.FirstOrDefault(e => e.AddressFamily.ToString().Equals("InterNetwork")).ToString();
        }


2.获取公网IP
public static bool TryGetInternetIp(out string internetIp)
        {
            internetIp = null;
            try
            {
                WebRequest wr = WebRequest.Create("http://www.ip138.com/ips138.asp");
                Stream s = wr.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(s, Encoding.Default);
                string all = sr.ReadToEnd(); //读取网站的数据
                int start = all.IndexOf("您的IP地址是:[", StringComparison.Ordinal) + 9;
                int end = all.IndexOf("]", start, StringComparison.Ordinal);
                sr.Close();
                s.Close();
                IPAddress result = null;
                if (IPAddress.TryParse(all.Substring(start, end - start), out result))
                {
                    internetIp = result.ToString();
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }




posted @ 2016-07-01 09:19  meazin  阅读(105)  评论(0编辑  收藏  举报