现在的位置: 首页 > 综合 > 正文

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

2013年07月04日 ⁄ 综合 ⁄ 共 1330字 ⁄ 字号 评论关闭

C#如何获取本机网络ip

有几种方法获取本机局域网地址和网络地址。

1.  获取本机局域网地址:

使用IPHostEntry

        static string GetLocalIp()
        {
            string hostname = Dns.GetHostName();
            IPHostEntry localhost = Dns.GetHostByName(hostname);
            IPAddress localaddr = localhost.AddressList[0];
            return localaddr.ToString();
        }

 

2. 获取本机网络ip地址

通过向网站http://www.ip138.com/ip2city.asp发送webrequest,分析返回的数据流

           try
           {
               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 i = all.IndexOf("[") + 1;
               string tempip = all.Substring(i, 15);
               string ip = tempip.Replace("]", "").Replace(" ", "").Replace("<","");     //去除杂项找出ip
               return ip;
           }

 

3. 获取本机网络ip地址和城市地址,webservices方式

利用网站webxml提供的获取ip的web services,在引用网站后取得ip地址

            try
            {
                webxmlIPservice.IpAddressSearchWebService WebIP = new webxmlIPservice.IpAddressSearchWebService();
                string[] strIP = WebIP.getGeoIPContext();
                return strIP[1];    //返回的数组0为ip地址,数组1为城市
            }

 

以下左下角为利用第3种方法获取的本地城市信息:

抱歉!评论已关闭.