Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

external IP-address in C#

Tags:

c#

What is the easiest way to get my external IP-address in C#?

like image 396
CSharp Avatar asked Dec 29 '22 00:12

CSharp


2 Answers

There's no built-in way to do it within the framework because it's hard to determine what the external/public IP address is. This of course is assuming your IP is NAT'ed behind some gateway.

One method would be to scrape a site like http://www.whatismyip.org/ using the WebClient class.

System.Net.WebClient client = new System.Net.WebClient();
string ip = client.DownloadString( "http://www.whatismyip.org" );
Console.Out.WriteLine( ip );
like image 63
Scott Saad Avatar answered Jan 08 '23 23:01

Scott Saad


public static string GetExternalIP()
{
     using (var wc = new System.Net.WebClient())
         return wc.DownloadString("http://whatismyip.org");
}
like image 35
Joel Coehoorn Avatar answered Jan 08 '23 21:01

Joel Coehoorn