C#如何获取本机网络IP地址

在开发过程中我们经常会碰到需要IP地址,用来记录用户上次登录的时间地址,或者sokect网络编程等等,下面介绍两种方式:

1.

public static string GetIP()
{
  return System.Web.HttpContext.Current.Request.UserHostAddress;
}

2.

public static string GetAddressIP()
{
  string strUrl = "http://www.ip138.com/ip2city.asp"; //获得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(); //读取网站返回的数据 格式:您的IP地址是:[x.x.x.x]
  int j = all.IndexOf("[");
  int k = all.IndexOf("]");
  string tempip = all.Substring(j + 1, k - j - 1);

  string ip = tempip.Replace("]", "").Replace(" ", "").Replace("<", "").Replace("/", ""); //去除杂项找出ip
  return ip;
}

原文地址:https://www.cnblogs.com/niguang/p/4717958.html