首页 > Windows开发 > 详细

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

时间:2015-08-10 14:44:18      阅读:217      评论:0      收藏:0      [点我收藏+]

在开发过程中我们经常会碰到需要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;
}

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

原文:http://www.cnblogs.com/niguang/p/4717958.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!