在局域网内获取本机的外部IP

博客指出在局域网中,使用“ipconfig.exe /all”和Dns.Resolve()只能获取内部IP,无法获取外部IP。研究表明,仅凭本机无法获得外部IP,需登录外网服务器,从服务器取回外部IP。

“ipconfig.exe /all”在局域网中只能获取内部IP, 无法获取本机的外部IP, Dns.Resolve()也一样。

经研究, 在局域网中, 仅凭本机的力量是无法获得本机的外部IP的, 必须登录到外网某个服务器, 那个服务器就知道你的IP, 然后你再取回来。

 1None.gifusing System;
 2None.gifusing System.IO;
 3None.gifusing System.Net;
 4None.gifusing System.Text.RegularExpressions;
 5None.gif
 6None.gifclass Test
 7ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 8InBlock.gif  // 获取网页的HTML内容
 9InBlock.gif  static string GetPage(string url)
10ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
11InBlock.gif    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
12InBlock.gif    try
13ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
14InBlock.gif      using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
15ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
16InBlock.gif        using (StreamReader sr = new StreamReader(res.GetResponseStream()))
17ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
18InBlock.gif          return sr.ReadToEnd();
19ExpandedSubBlockEnd.gif        }

20ExpandedSubBlockEnd.gif      }

21ExpandedSubBlockEnd.gif    }

22InBlock.gif    catch (System.Exception e)
23ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
24InBlock.gif      return e.Message;
25ExpandedSubBlockEnd.gif    }

26InBlock.gif    finally
27ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
28InBlock.gif      req.Abort();
29ExpandedSubBlockEnd.gif    }

30ExpandedSubBlockEnd.gif  }

31InBlock.gif
32InBlock.gif  // 通过外部网站得到本机的外部IP
33InBlock.gif  static string GetOuterIP()
34ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
35InBlock.gif    string patt = @"IP: \[(?<IP>[0-9\.]*)\]";
36InBlock.gif    string url  = "http://www.skyiv.com/info";
37InBlock.gif    return Regex.Match(GetPage(url), patt).Groups["IP"].Value;
38ExpandedSubBlockEnd.gif  }

39InBlock.gif
40InBlock.gif  static void Main()
41ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
42InBlock.gif    Console.WriteLine("Inner IP:");
43InBlock.gif    foreach (IPAddress ip in Dns.Resolve(Dns.GetHostName()).AddressList)
44ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
45InBlock.gif      Console.WriteLine(ip);
46ExpandedSubBlockEnd.gif    }

47InBlock.gif    Console.WriteLine();
48InBlock.gif    Console.WriteLine("Outer IP:");
49InBlock.gif    Console.WriteLine(GetOuterIP());
50ExpandedSubBlockEnd.gif  }

51ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/skyiv/archive/2005/10/01/GetIP.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值