我想通过我的机器连接到互联网上的IP地址

问题描述:

可能重复:
c# Get public/external IP address?我想通过我的机器连接到互联网上的IP地址

我开发的C#应用​​程序中,我需要找到用于连接到互联网的公共IP地址。我怎么能得到这个?

您可以使用http://showip.codebrainz.ca/来获得它。更多信息here

代码示例:

using System; 
using System.Net; 

class Program 
{ 
    static void Main() 
    { 
    // Create web client. 
    WebClient client = new WebClient(); 

    // Download string. 
    string ip = client.DownloadString("http://showip.codebrainz.ca/"); 

    // Write ip. 
    Console.WriteLine(ip); 
    } 
} 
+0

这对我没有用我想要得到我的路由器IP – Ayush

+0

这给你你的PUBLIC IP。 – rickythefox

获取公网IP地址的最简单的方法已经由其他海报解决。有一些替代方案,但它们是情境性的(如需要支持SNMP的路由器的SNMP)。

如果你想要一种方法,它不仅可以让你获得公共IP地址,还可以测试你如何连接到互联网(例如对称NAT,全锥体,直接连接等),你可以使用STUN协议(见RFC 5389)。 STUN还要求您联系外部STUN服务器。

如果您想要示例,Ivar Lumi在codeproject上发布了一些working c# code。根据您的要求,这可能是矫枉过正。

+0

我得到了ans我的问题 – Ayush

+0

WebClient client = new WebClient(); client.Headers.Add(“user-agent”,“Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.2; .NET CLR1.0.3705;)”); string baseurl =“http://checkip.dyndns.org/”; 流数据= client.OpenRead(baseurl); StreamReader reader = new StreamReader(data); string s = reader.ReadToEnd(); data.Close(); reader.Close(); S = s.Replace( “

当前IP检查”, “”).Replace( “”, “”)的ToString(); MessageBox.Show(s); – Ayush
+0

基本上其他海报写的 - 你应该upvote他们的答案;) – Anthill