Get public/external IP address?

前端 未结 26 1954
鱼传尺愫
鱼传尺愫 2020-11-22 14:32

I cant seem to get or find information on finding my routers public IP? Is this because it cant be done this way and would have to get it from a website?

相关标签:
26条回答
  • 2020-11-22 14:59

    With a few lines of code you can write your own Http Server for this.

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

    Then anytime you need to know your public ip, you can do this.

    WebClient client = new WebClient();
    string ip = client.DownloadString("http://serverIp/PublicIP");
    
    0 讨论(0)
  • 2020-11-22 14:59
    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"; }
    }
    

    Used loopback as fallback just so things don't fatally break.

    0 讨论(0)
提交回复
热议问题