Get public/external IP address?

前端 未结 26 1952
鱼传尺愫
鱼传尺愫 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:42

    Most of the answers have mentioned http://checkip.dyndns.org in solution. For us, it didn't worked out well. We have faced Timemouts a lot of time. Its really troubling if your program is dependent on the IP detection.

    As a solution, we use the following method in one of our desktop applications:

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

    Good part is, both sites return IP in plain format. So string operations are avoided.

    To check your logic in catch clause, you can reproduce Timeout by hitting a non available port. eg: http://checkip.amazonaws.com:81/

提交回复
热议问题