码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2015-08-10 14:46:17      阅读:104      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!