Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get local IP address

Tags:

c#

networking

In the internet there are several places that show you how to get an IP address. And a lot of them look like this example:

String strHostName = string.Empty; // Getting Ip address of local machine... // First get the host name of local machine. strHostName = Dns.GetHostName(); Console.WriteLine("Local Machine's Host Name: " + strHostName); // Then using host name, get the IP address list.. IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); IPAddress[] addr = ipEntry.AddressList;  for (int i = 0; i < addr.Length; i++) {     Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString()); } Console.ReadLine(); 

With this example I get several IP addresses, but I'm only interested in getting the one that the router assigns to the computer running the program: the IP that I would give to someone if he wishes to access a shared folder in my computer for instance.

If I am not connected to a network and I am connected to the internet directly via a modem with no router then I would like to get an error. How can I see if my computer is connected to a network with C# and if it is then to get the LAN IP address.

like image 261
Tono Nam Avatar asked Jul 23 '11 20:07

Tono Nam


People also ask

How do I get my IP address in CMD?

First, click on your Start Menu and type cmd in the search box and press enter. A black and white window will open where you will type ipconfig /all and press enter. There is a space between the command ipconfig and the switch of /all. Your ip address will be the IPv4 address.


1 Answers

To get local Ip Address:

public static string GetLocalIPAddress() {     var host = Dns.GetHostEntry(Dns.GetHostName());     foreach (var ip in host.AddressList)     {         if (ip.AddressFamily == AddressFamily.InterNetwork)         {             return ip.ToString();         }     }     throw new Exception("No network adapters with an IPv4 address in the system!"); } 

To check if you're connected or not:

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

like image 82
Mrchief Avatar answered Sep 16 '22 14:09

Mrchief