Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the Local Network IP address of a computer programmatically?

I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.

How can I accomplish this?

like image 290
Lawrence Johnston Avatar asked Sep 29 '08 23:09

Lawrence Johnston


People also ask

How do I find the IP address of a local network device?

To see all of the devices connected to your network, type arp -a in a Command Prompt window. This will show you the allocated IP addresses and the MAC addresses of all connected devices.

How do you find all IP address in LAN using CMD?

From the desktop, navigate through; Start > Run> type "cmd.exe". A command prompt window will appear. At the prompt, type "ipconfig /all". All IP information for all network adapters in use by Windows will be displayed.

How do I find my local IP C++?

You can use gethostname followed by gethostbyname to get your local interface internal IP.

How can I get local IP address in C#?

By passing the hostname to GetHostByName() method we will get the IP Address. This method returns a structure of type hostent for the specified host name. AddressList[0] gives the ip address and ToString() method is used to convert it to string.


1 Answers

If you are looking for the sort of information that the command line utility, ipconfig, can provide, you should probably be using the System.Net.NetworkInformation namespace.

This sample code will enumerate all of the network interfaces and dump the addresses known for each adapter.

using System; using System.Net; using System.Net.NetworkInformation;  class Program {     static void Main(string[] args)     {         foreach ( NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces() )         {             Console.WriteLine("Network Interface: {0}", netif.Name);             IPInterfaceProperties properties = netif.GetIPProperties();             foreach ( IPAddress dns in properties.DnsAddresses )                 Console.WriteLine("\tDNS: {0}", dns);             foreach ( IPAddressInformation anycast in properties.AnycastAddresses )                 Console.WriteLine("\tAnyCast: {0}", anycast.Address);             foreach ( IPAddressInformation multicast in properties.MulticastAddresses )                 Console.WriteLine("\tMultiCast: {0}", multicast.Address);             foreach ( IPAddressInformation unicast in properties.UnicastAddresses )                 Console.WriteLine("\tUniCast: {0}", unicast.Address);         }     } } 

You are probably most interested in the UnicastAddresses.

like image 125
GBegen Avatar answered Oct 09 '22 21:10

GBegen