c#, aspx, .net

ITsolutionWizard
ITsolutionWizard used Ask the Experts™
on
I have below codes to get IP. In my office, it return lan IP. how can i get the public router IP?

  public string GetIP()
        {
            string strHostName = "";
            strHostName = System.Net.Dns.GetHostName();
            IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            return addr[addr.Length - 1].ToString();
        }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Quick and dirty method; bounce a request off of an external service; e.g. -
string pubIp =  new System.Net.WebClient().DownloadString("https://api.ipify.org");

Open in new window

Slightly more involved method, stand-up your own HttpServer; e.g. -
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();
}

Open in new window

Point an external Dns Record at an instance of the above server and call the server instance; e.g. -
WebClient client = new WebClient();
string ip = client.DownloadString("http://HttpServerDnsAddress/PublicIP");

Open in new window


Slightly more involved method will not work if you are making a loopback request.

-saige-

Author

Commented:
So which one should be used?
Commented:
I would start with the first method to get things running.  At some point it would be beneficial to see about doing the second method so that you are not depended on a 3rd party.

-saige-
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

Split:
-- it_saige (https:#a42080100)
-- it_saige (https:#a42080396)


If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

frankhelk
Experts-Exchange Cleanup Volunteer

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial