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?
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.
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.
You can use gethostname followed by gethostbyname to get your local interface internal IP.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With