当前位置:首页 > Windows程序 > 正文

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

2021-03-27 Windows程序

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("http://www.mamicode.com/", ""); //去除杂项找出ip
  return ip;
}

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/68637.html