获得公网ip

jieon 2009-09-10 12:59:39
winform如何获得本机的ip地址,如是公网的话直接返回公网ip。
string strHostName = Dns.GetHostName();
clientAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
这样得到的总是内网段的ip....
如在公网,可以直接获取吗?
...全文
88 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
jieon 2009-09-10
  • 打赏
  • 举报
回复
foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
Console.WriteLine(ip);
}
wuyq11 2009-09-10
  • 打赏
  • 举报
回复
static string GetPage(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
try
{
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
catch (System.Exception e)
{
return e.Message;
}
finally
{
req.Abort();
}
}
// 通过外部网站得到本机的外部IP
static string GetOuterIP()
{
string patt = @"IP: \[(?<IP>[0-9\.]*)\]";
string url = "";
return Regex.Match(GetPage(url), patt).Groups["IP"].Value;
}

static void Main()
{
foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
Console.WriteLine(ip);
}
Console.WriteLine();
Console.WriteLine(GetOuterIP());
}
jieon 2009-09-10
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 caozhy 的回复:]
引用 4 楼 jieon 的回复:
我的意图是在程序运行的时候判断是自身是内网,还是公网

10 127 169 172 192 ... 这些网段是内网。
或者把公网和本地ip比较,判断。
[/Quote]
我是把得到ip得到的ip在内网网段内比较,可我发现公网得到的ip它也会在内网网段内....
threenewbee 2009-09-10
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 jieon 的回复:]
我的意图是在程序运行的时候判断是自身是内网,还是公网
[/Quote]
10 127 169 172 192 ... 这些网段是内网。
或者把公网和本地ip比较,判断。
jieon 2009-09-10
  • 打赏
  • 举报
回复
我的意图是在程序运行的时候判断是自身是内网,还是公网
lzsh0622 2009-09-10
  • 打赏
  • 举报
回复
网关内,不通过外部网络,得不到.
jieon 2009-09-10
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 caozhy 的回复:]
不可以。需要公网段反射回来。

比如访问www.ip138.com,然后读取返回的网页。
[/Quote]
这样内网的机器访问 返回的也会是公网ip
threenewbee 2009-09-10
  • 打赏
  • 举报
回复
不可以。需要公网段反射回来。

比如访问www.ip138.com,然后读取返回的网页。

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧