获取公共/外部IP地址?

arb*_*bme 55 c# networking ip-address

我似乎无法获得或找到有关找到我的路由器公共IP的信息?这是因为它不能以这种方式完成并且必须从网站上获取它吗?

use*_*r_v 90

使用C#,webclient是一个简短的.

public static void Main(string[] args)
{
    string externalip = new WebClient().DownloadString("http://icanhazip.com");            
    Console.WriteLine(externalip);
}
Run Code Online (Sandbox Code Playgroud)

命令行(适用于Linux和Windows)

wget -qO- http://bot.whatismyipaddress.com
Run Code Online (Sandbox Code Playgroud)

要么

curl http://ipinfo.io/ip
Run Code Online (Sandbox Code Playgroud)

  • 很棒的答案!顺便说一句,我不得不对`http:// ipinfo.io/ip`的结果调用`Trim()`.有一个尾随空间. (7认同)
  • 这将获得*服务器的* IP 地址而不是用户的 IP 地址。 (3认同)

小智 70

static void Main(string[] args)
{
    HTTPGet req = new HTTPGet();
    req.Request("http://checkip.dyndns.org");
    string[] a = req.ResponseBody.Split(':');
    string a2 = a[1].Substring(1);
    string[] a3=a2.Split('<');
    string a4 = a3[0];
    Console.WriteLine(a4);
    Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

使用Check IP DNS执行此小操作

使用HTTPGet在Goldb-Httpget C#上找到的类#

  • HttpGet在上面提到的网址上不再存在,请更新 (3认同)

r.z*_*rei 37

使用.Net WebRequest:

  public static string GetPublicIP()
    {
        string url = "http://checkip.dyndns.org";
        System.Net.WebRequest req = System.Net.WebRequest.Create(url);
        System.Net.WebResponse resp = req.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
        string response = sr.ReadToEnd().Trim();
        string[] a = response.Split(':');
        string a2 = a[1].Substring(1);
        string[] a3 = a2.Split('<');
        string a4 = a3[0];
        return a4;
    }
Run Code Online (Sandbox Code Playgroud)


sun*_*nga 30

string pubIp =  new System.Net.WebClient().DownloadString("https://api.ipify.org");
Run Code Online (Sandbox Code Playgroud)


Ric*_*chi 22

类似的服务

private string GetPublicIpAddress()
{
    var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");

    request.UserAgent = "curl"; // this will tell the server to return the information as if the request was made by the linux "curl" command

    string publicIPAddress;

    request.Method = "GET";
    using (WebResponse response = request.GetResponse())
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            publicIPAddress = reader.ReadToEnd();
        }
    }

    return publicIPAddress.Replace("\n", "");
}
Run Code Online (Sandbox Code Playgroud)


Nol*_*rin 13

从理论上讲,您的路由器应该能够告诉您网络的公共IP地址,但是这样做的方式必然是不一致/非直接的,即使对某些路由器设备也是如此.

最简单且仍然非常可靠的方法是向网页发送请求,该网页会在Web服务器看到它时返回您的IP地址.Dyndns.org为此提供了良好的服务:

http://checkip.dyndns.org/

返回的是一个非常简单/简短的HTML文档,其中包含文本Current IP Address: 157.221.82.39(伪IP),从HTTP响应中提取这些文本很简单.


Sho*_*Sha 11

@ suneel ranga扩展了这个答案:

static System.Net.IPAddress GetPublicIp(string serviceUrl = "https://ipinfo.io/ip")
{
    return System.Net.IPAddress.Parse(new System.Net.WebClient().DownloadString(serviceUrl));
}
Run Code Online (Sandbox Code Playgroud)

您将使用的服务System.Net.WebClient只是将IP地址显示为字符串并使用该System.Net.IPAddress对象.以下是一些此类服务*:

*此问题中提到了一些服务,并且来自超级用户网站的这些答案.

  • +1 在前面添加“https”。我不知道为什么这里的大多数人认为通过“http”请求外部IP是正常的。顺便说一句,“checkip.amazonaws.com”现在支持 ssl。 (2认同)

Dow*_*ers 8

我发现http://checkip.dyndns.org/给了我必须处理的html标签,但https://icanhazip.com/只给了我一个简单的字符串.不幸的是,https: //icanhazip.com/给了我ip6地址,我需要ip4.幸运的是,您可以选择2个子域名,ipv4.icanhazip.com和ipv6.icanhazip.com.

        string externalip = new WebClient().DownloadString("https://ipv4.icanhazip.com/");
        Console.WriteLine(externalip);
        Console.WriteLine(externalip.TrimEnd());
Run Code Online (Sandbox Code Playgroud)


Des*_*tar 6

只需几行代码,您就可以编写自己的Http Server.

HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://+/PublicIP/");
listener.Start();
while (true)
{
    HttpListenerContext context = listener.GetContext();
    string clientIP = context.Request.RemoteEndPoint.Address.ToString();
    using (Stream response = context.Response.OutputStream)
    using (StreamWriter writer = new StreamWriter(response))
        writer.Write(clientIP);

    context.Response.Close();
}
Run Code Online (Sandbox Code Playgroud)

然后,只要你需要知道你的公共IP,你就可以做到这一点.

WebClient client = new WebClient();
string ip = client.DownloadString("http://serverIp/PublicIP");
Run Code Online (Sandbox Code Playgroud)


Top*_*rak 6

快速获取没有任何连接的外部IP的方法Actualy不需要任何Http连接

首先你必须在Referance上添加NATUPNPLib.dll并从referances中选择它并从属性窗口中检查Embed Interop Type为False

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NATUPNPLib; // Add this dll from referance and chande Embed Interop Interop to false from properties panel on visual studio
using System.Net;

namespace Client
{
    class NATTRAVERSAL
    {
        //This is code for get external ip
        private void NAT_TRAVERSAL_ACT()
        {
            UPnPNATClass uPnP = new UPnPNATClass();
            IStaticPortMappingCollection map = uPnP.StaticPortMappingCollection;

            foreach (IStaticPortMapping item in map)
            {
                    Debug.Print(item.ExternalIPAddress); //This line will give you external ip as string
                    break;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 要使NATUPNPLib工作,需要在路由器中启用UPnP,这是[安全问题](http://www.google.co.uk/search?q=router+upnp+security). (3认同)

Dev*_*per 6

基本上我更喜欢使用一些额外的备份,以防其中一个 IP 无法访问。所以我用这个方法。

 public static string GetExternalIPAddress()
        {
            string result = string.Empty;
            try
            {
                using (var client = new WebClient())
                {
                    client.Headers["User-Agent"] =
                    "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
                    "(compatible; MSIE 6.0; Windows NT 5.1; " +
                    ".NET CLR 1.1.4322; .NET CLR 2.0.50727)";

                    try
                    {
                        byte[] arr = client.DownloadData("http://checkip.amazonaws.com/");

                        string response = System.Text.Encoding.UTF8.GetString(arr);

                        result = response.Trim();
                    }
                    catch (WebException)
                    {                       
                    }
                }
            }
            catch
            {
            }

            if (string.IsNullOrEmpty(result))
            {
                try
                {
                    result = new WebClient().DownloadString("https://ipinfo.io/ip").Replace("\n", "");
                }
                catch
                {
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                try
                {
                    result = new WebClient().DownloadString("https://api.ipify.org").Replace("\n", "");
                }
                catch
                {
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                try
                {
                    result = new WebClient().DownloadString("https://icanhazip.com").Replace("\n", "");
                }
                catch
                {
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                try
                {
                    result = new WebClient().DownloadString("https://wtfismyip.com/text").Replace("\n", "");
                }
                catch
                {
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                try
                {
                    result = new WebClient().DownloadString("http://bot.whatismyipaddress.com/").Replace("\n", "");
                }
                catch
                {
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                try
                {
                    string url = "http://checkip.dyndns.org";
                    System.Net.WebRequest req = System.Net.WebRequest.Create(url);
                    System.Net.WebResponse resp = req.GetResponse();
                    System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                    string response = sr.ReadToEnd().Trim();
                    string[] a = response.Split(':');
                    string a2 = a[1].Substring(1);
                    string[] a3 = a2.Split('<');
                    result = a3[0];
                }
                catch (Exception)
                {
                }
            }

            return result;
        }
Run Code Online (Sandbox Code Playgroud)

为了更新 GUI 控件(WPF、.NET 4.5),例如一些标签,我使用此代码

 void GetPublicIPAddress()
 {
            Task.Factory.StartNew(() =>
            {
                var ipAddress = SystemHelper.GetExternalIPAddress();

                Action bindData = () =>
                {
                    if (!string.IsNullOrEmpty(ipAddress))
                        labelMainContent.Content = "IP External: " + ipAddress;
                    else
                        labelMainContent.Content = "IP External: ";

                    labelMainContent.Visibility = Visibility.Visible; 
                };
                this.Dispatcher.InvokeAsync(bindData);
            });

 }
Run Code Online (Sandbox Code Playgroud)

希望它有用。

这是包含此代码的应用程序示例。

  • 那_不能_失败!:) (3认同)

Jes*_*per 6

我发现大多数其他答案都缺乏,因为他们假设任何返回的字符串都必须是 IP,但并没有真正检查它。这是我目前正在使用的解决方案。它只会返回有效的 IP,如果没有找到,则返回 null。

public class WhatsMyIp
{
    public static IPAddress PublicIp { get; private set; }
    static WhatsMyIp()
    {
        PublicIp = GetMyIp();
    }

    public static IPAddress GetMyIp()
    {
        List<string> services = new List<string>()
        {
            "https://ipv4.icanhazip.com",
            "https://api.ipify.org",
            "https://ipinfo.io/ip",
            "https://checkip.amazonaws.com",
            "https://wtfismyip.com/text",
            "http://icanhazip.com"
        };
        using (var webclient = new HttpClient())
            foreach (var service in services)
            {
                try { return IPAddress.Parse(webclient.GetStringAsync(service).Result); } catch { }
            }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)


ole*_*rch 5

checkip.dyndns.org并非总是能正常工作。例如,对于我的机器,它显示内部的NAT后地址:

Current IP Address: 192.168.1.120
Run Code Online (Sandbox Code Playgroud)

我认为它的发生是因为我在NAT后面有我的本地DNS区域,并且我的浏览器发送了校验它的本地IP地址,并将其返回。

另外,http是重量级且基于文本的基于TCP的协议,因此不太适合快速有效地定期请求外部IP地址。我建议使用基于UDP的二进制STUN,它是专门为此目的而设计的:

http://en.wikipedia.org/wiki/STUN

STUN服务器就像“ UDP镜像”。您期待着它,然后看到“我的样子”。

世界上有许多公共STUN服务器,您可以在其中请求外部IP。例如,在这里:

http://www.voip-info.org/wiki/view/STUN

您可以从Internet下载任何STUN客户端库,例如,在这里:

http://www.codeproject.com/Articles/18492/STUN-Client

并使用它。