获取公共/外部IP地址?获取公共/外部IP地址?(Get public/external IP ad

2019-05-10 16:02发布

我似乎无法得到或找到找到我的路由器的公网IP的信息? 这是因为它不能做到这样的,就必须从网站得到它?

Answer 1:

从C#中,你可以使用Web客户端库获取whatismyip



Answer 2:

使用C#,随着Web客户端的短单。

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

命令行 (适用于Linux和Windows)

wget -qO- http://bot.whatismyipaddress.com

要么

curl http://ipinfo.io/ip


Answer 3:

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();
}

做的这个小把戏与检查DNS IP

使用HTTPGet I类上找到Goldb-HTTPGET C#



Answer 4:

使用.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;
    }


Answer 5:

string pubIp =  new System.Net.WebClient().DownloadString("https://api.ipify.org");


Answer 6:

类似的服务

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

            request.UserAgent = "curl"; // this simulate curl linux 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", "");
        }


Answer 7:

从理论上讲你的路由器应该能够告诉你网络的公网IP地址,但这样做的方式必然是不一致/非直接的,如果甚至有可能与某些路由器设备。

最简单,仍然是一个非常可靠的方法是发送到Web页面作为Web服务器看到它,返回你的IP地址的请求。 Dyndns.org为此提供了一个良好的服务:

http://checkip.dyndns.org/

什么是返回是一个非常简单的/短的HTML文档,包含文本Current IP Address: 157.221.82.39 (假IP),这是微不足道的,从HTTP响应中提取。



Answer 8:

扩展在此答案由@ suneel朗高 :

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

在这里您将使用与服务System.Net.WebClient ,仅仅显示了IP地址作为一个字符串,并使用System.Net.IPAddress对象。 这里有几个这样的服务*:

  • https://ipinfo.io/ip/
  • https://api.ipify.org/
  • https://icanhazip.com/
  • http://checkip.amazonaws.com/ (无SSL)
  • https://wtfismyip.com/text
  • https://myip.dnsdynamic.com/ (虽然身份不被信任和加密是过时)

*有些服务是在这个问题上,并从这些提到的超级用户现场解答 。



Answer 9:

随着几行代码,你可以写这个你自己的HTTP服务器。

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();
}

然后,任何时候你需要知道你的公网IP,你可以做到这一点。

WebClient client = new WebClient();
string ip = client.DownloadString("http://serverIp/PublicIP");


Answer 10:

快速的方式来获得外部IP没有任何Actualy连接不需要任何HTTP连接

首先,你必须在全球化志愿服务青年加入NATUPNPLib.dll而且从referances选择它,然后从属性窗口中嵌入互操作类型检查假

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;
            }
        }
    }
}


Answer 11:

checkip.dyndns.org并不总是正常工作。 例如,我的机器就说明内部后,NAT地址:

Current IP Address: 192.168.1.120

我认为它的发生,因为我有NAT后面我的本地DNS区,和我的浏览器发送到checkip其本地IP地址,这是返回。

此外,HTTP是沉重的重量和面向文本的基于TCP的协议,因此不是很适合于外部IP地址快速和有效的定期请求。 我建议使用基于UDP的,二进制STUN,专为这个目的:

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

STUN服务器就像是“UDP镜”。 你看它,看看“我怎么看起来”。

有许多公共STUN的服务器遍布世界各地,在那里你可以要求你的外部IP。 例如,在这里看到:

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

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

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

并使用它。



Answer 12:

我发现, 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());


Answer 13:

我用它HttpClientSystem.Net.Http

public static string PublicIPAddress()
{
    string uri = "http://checkip.dyndns.org/";
    string ip = String.Empty;

    using (var client = new HttpClient())
    {
        var result = client.GetAsync(uri).Result.Content.ReadAsStringAsync().Result;

        ip = result.Split(':')[1].Split('<')[0];
    }

    return ip;
}


Answer 14:

public static string GetPublicIP()
{
    return new System.Net.WebClient().DownloadString("https://ipinfo.io/ip").Replace("\n","");
}


Answer 15:

基本上我比较喜欢的情况下,使用一些额外的备份,如果其中一个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;
        }

为了更新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);
            });

 }

希望这是有益的。

这是应用的一个例子,其中将包括该代码。



Answer 16:

当我调试,我用下面的构造可调用的外部URL,但你可以只使用前两行让你的公网IP:

public static string ExternalAction(this UrlHelper helper, string actionName, string controllerName = null, RouteValueDictionary routeValues = null, string protocol = null)
{
#if DEBUG
    var client = new HttpClient();
    var ipAddress = client.GetStringAsync("http://ipecho.net/plain").Result; 
    // above 2 lines should do it..
    var route = UrlHelper.GenerateUrl(null, actionName, controllerName, routeValues, helper.RouteCollection, helper.RequestContext, true); 
    if (route == null)
    {
        return route;
    }
    if (string.IsNullOrEmpty(protocol) && string.IsNullOrEmpty(ipAddress))
    {
        return route;
    }
    var url = HttpContext.Current.Request.Url;
    protocol = !string.IsNullOrWhiteSpace(protocol) ? protocol : Uri.UriSchemeHttp;
    return string.Concat(protocol, Uri.SchemeDelimiter, ipAddress, route);
#else
    helper.Action(action, null, null, HttpContext.Current.Request.Url.Scheme)
#endif
}


Answer 17:

基于使用外部Web服务的答案是不完全正确的,因为他们并没有真正回答说问题:

......上找到我的路由器的公网IP信息


说明

所有在线服务来回报外部IP地址, 但它基本上不意味着,这个地址被分配给用户的路由器。

路由器可以与ISP基础设施网络的另一个本地IP地址进行分配。 实际上,这意味着,路由器不能承载在互联网上提供的任何服务。 这可能是适合大多数家庭用户的安全性,但对于怪才谁主服务器在家里也不好。

以下是如何检查,如果路由器有外部IP:

根据维基百科的文章,该IP地址范围10.0.0.0 – 10.255.255.255172.16.0.0 – 172.31.255.255192.168.0.0 – 192.168.255.255用于私有即本地网络。

看到当你跟踪路由与路由器所具有的外部IP地址分配给某些远程主机会发生什么:

疑难杂症! 第一跳开始,从31.*现在。 这显然意味着,有您的路由器和Internet之间没有什么。


  1. 让平与某个地址Ttl = 2
  2. 评价在何处响应来自。

TTL = 2必须不足以达到远程主机。 合#1的主机会发出"Reply from <ip address>: TTL expired in transit." 揭示其IP地址。

履行

try
{
    using (var ping = new Ping())
    {
        var pingResult = ping.Send("google.com");
        if (pingResult?.Status == IPStatus.Success)
        {
            pingResult = ping.Send(pingResult.Address, 3000, "ping".ToAsciiBytes(), new PingOptions { Ttl = 2 });

            var isRealIp = !Helpers.IsLocalIp(pingResult?.Address);

            Console.WriteLine(pingResult?.Address == null
                ? $"Has {(isRealIp ? string.Empty : "no ")}real IP, status: {pingResult?.Status}"
                : $"Has {(isRealIp ? string.Empty : "no ")}real IP, response from: {pingResult.Address}, status: {pingResult.Status}");

            Console.WriteLine($"ISP assigned REAL EXTERNAL IP to your router, response from: {pingResult?.Address}, status: {pingResult?.Status}");
        }
        else
        {
            Console.WriteLine($"Your router appears to be behind ISP networks, response from: {pingResult?.Address}, status: {pingResult?.Status}");
        }
    }
}
catch (Exception exc)
{
    Console.WriteLine("Failed to resolve external ip address by ping");
}

小助手用来检查IP属于私人或公共网络:

public static bool IsLocalIp(IPAddress ip) {
    var ipParts = ip.ToString().Split(new [] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();

    return (ipParts[0] == 192 && ipParts[1] == 168) 
        || (ipParts[0] == 172 && ipParts[1] >= 16 && ipParts[1] <= 31) 
        ||  ipParts[0] == 10;
}


Answer 18:

最佳答案我发现

要获取远程IP地址以最快的方式。 您必须使用一个下载器,或在您的计算机上的服务器。

使用这个简单的代码的缺点:(推荐)是,这将需要3-5秒,让您的远程IP地址,因为初始化时,Web客户端始终以3-5秒,以检查您的代理设置。

 public static string GetIP()
 {
            string externalIP = "";
            externalIP = new WebClient().DownloadString("http://checkip.dyndns.org/");
            externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                           .Matches(externalIP)[0].ToString();
            return externalIP;
 }

这是我如何修复它。(第一次还是需要3-5秒),但之后,它总是会得到你的远程IP地址在0-2秒,这取决于你的连接。

public static WebClient webclient = new WebClient();
public static string GetIP()
{
    string externalIP = "";
    externalIP = webclient.DownloadString("http://checkip.dyndns.org/");
    externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                   .Matches(externalIP)[0].ToString();
    return externalIP;
}


Answer 19:

大部分的答案都提到http://checkip.dyndns.org在溶液中。 对我们来说,它并没有制定出很好。 我们曾面临Timemouts了大量的时间。 它真的困扰,如果你的程序是依赖于IP检测。

作为一个解决方案,我们用下面的方法在我们的桌面应用程序之一:

    // Returns external/public ip
    protected string GetExternalIP()
    {
        try
        {
            using (MyWebClient client = new MyWebClient())
            {
                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);

                    return response.Trim();
                }
                catch (WebException ex)
                {
                    // Reproduce timeout: http://checkip.amazonaws.com:81/

                    // trying with another site
                    try
                    {
                        byte[] arr = client.DownloadData("http://icanhazip.com/");

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

                        return response.Trim();
                    }
                    catch (WebException exc)
                    { return "Undefined"; }
                }
            }
        }
        catch (Exception ex)
        {
            // TODO: Log trace
            return "Undefined";
        }
    }

良好的部分是,这两个网站以纯格式返回IP。 所以字符串操作避免。

要检查你的逻辑catch条款,您可以通过点击一个非可用的端口复制超时。 例如: http://checkip.amazonaws.com:81/



Answer 20:

该IPIFY API是很好的,因为它可以在原始文本和JSON响应。 它也可以做回调等等。唯一的问题是,它在IPv4中,而不是6响应。



Answer 21:

public string GetClientIp() {
    var ipAddress = string.Empty;
    if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) {
        ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    } else if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null &&
               System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"].Length != 0) {
        ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
    } else if (System.Web.HttpContext.Current.Request.UserHostAddress.Length != 0) {
        ipAddress = System.Web.HttpContext.Current.Request.UserHostName;
    }
    return ipAddress;
} 

完美的作品



Answer 22:

using System.Net;

private string GetWorldIP()
{
    String url = "http://bot.whatismyipaddress.com/";
    String result = null;

    try
    {
        WebClient client = new WebClient();
        result = client.DownloadString(url);
        return result;
    }
    catch (Exception ex) { return "127.0.0.1"; }
}

二手回环作为后备只是让事情不会致命破。



Answer 23:

您可以使用远程登录以编程方式查询您的广域网IP路由器。

而远程部分

而远程部分可以使用完成,例如, 这种简约的Telnet代码为API发送Telnet命令到路由器,并得到路由器的回应。 在这个答案的其余部分假定你是设立在这种或那种方式发送Telnet命令,并取回你的代码的响应。

的方法局限性

我会说在前面,相比其他方法查询路由器的一个缺点是,你写的代码很可能是相当具体到你的路由器型号。 这就是说,它可以是不依赖于外部服务器一个有用的方法,你可能无论如何希望从自己的软件来访问你的路由器用于其他目的,如配置和控制它,使它更有价值编写特定的代码。

示例路由器命令和响应

下面的例子将不适合所有路由器,但说明了原则的做法。 你将需要改变,以适应你的路由器命令和响应的细节。

例如,顺便让你的路由器显示WAN IP可能是以下Telnet命令:

connection list

输出可以包括文本行,每个连接一体,具有IP地址的列表中的偏移39. WAN连接线既可以是从词“互联网”在某处线识别:

  RESP: 3947  17.110.226. 13:443       146.200.253. 16:60642     [R..A] Internet      6 tcp   128
<------------------  39  -------------><--  WAN IP -->

输出可填补每个IP地址段出三个字符用空格,你将需要删除。 (也就是说,在上面的xample,你需要把“146.200.253。16”到“146.200.253.16”。)

通过实验或路由器的咨询参考文档,你可以建立用于特定的路由器,以及如何解释路由器的响应的命令。

代码来获取WAN IP

(假设你有一个方法sendRouterCommand为Telnet部分见上)。

使用上述例子路由器,下面的代码获取WAN IP:

private bool getWanIp(ref string wanIP)
{
    string routerResponse = sendRouterCommand("connection list");

    return (getWanIpFromRouterResponse(routerResponse, out wanIP));
}

private bool getWanIpFromRouterResponse(string routerResponse, out string ipResult)
{
    ipResult = null;
    string[] responseLines = routerResponse.Split(new char[] { '\n' });

    //  RESP: 3947  17.110.226. 13:443       146.200.253. 16:60642     [R..A] Internet      6 tcp   128
    //<------------------  39  -------------><---  15   --->

    const int offset = 39, length = 15;

    foreach (string line in responseLines)
    {
        if (line.Length > (offset + length) && line.Contains("Internet"))
        {
            ipResult = line.Substring(39, 15).Replace(" ", "");
            return true;
        }
    }

    return false;
}


Answer 24:

我重构@Academy程序员的回答更短的代码,并改变它,使它只命中https://的网址:

    public static string GetExternalIPAddress()
    {
        string result = string.Empty;

        string[] checkIPUrl =
        {
            "https://ipinfo.io/ip",
            "https://checkip.amazonaws.com/",
            "https://api.ipify.org",
            "https://icanhazip.com",
            "https://wtfismyip.com/text"
        };

        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)";

            foreach (var url in checkIPUrl)
            {
                try
                {
                    result = client.DownloadString(url);
                }
                catch
                {
                }

                if (!string.IsNullOrEmpty(result))
                    break;
            }
        }

        return result.Replace("\n", "").Trim();
    }
}


Answer 25:

还是这个,它工作得很好,我认为我需要的东西。 这是从这里 。

public IPAddress GetExternalIP()
{
    WebClient lol = new WebClient();
    string str = lol.DownloadString("http://www.ip-adress.com/");
    string pattern = "<h2>My IP address is: (.+)</h2>"
    MatchCollection matches1 = Regex.Matches(str, pattern);
    string ip = matches1(0).ToString;
    ip = ip.Remove(0, 21);
    ip = ip.Replace("

    ", "");
    ip = ip.Replace(" ", "");
    return IPAddress.Parse(ip);
}


文章来源: Get public/external IP address?