Microsoft .NET have a mature API to play and code against the network you are connected. All the information you need to do that resides under System.Net
and its sub namespace.
This article will cover the simplest part of all and provide a way on how to get the IP Address of (my) machine using C# and LINQ. I know you would have read tons of pages with the same title, but with LINQ is the special on plate today. Lets get familiar with few object first.
The static class DNS under System.Net
namespace provides the information about the Domain Name System (DNS) of any system for IP Address provided or for the local system. This class can be used to get the Host name of the local machine or can also be used to reterive the IP Address of the machine if host name is already known.
Another important class is IPHostEntry
which behaves as a container for Internet host address information. Object of this class contains the address information for any host name.
The class IPAddress
is .NET representation of ip address and contains useful methods to play with the IP address like Parse
(from string), TryParse
(to validate and convert to IP address) etc.
An IP Address can belong to one of the AddressFamily
category. Below shows the list of member in the AddressFamily
enumeration. It also contains Unknown and Unspecified category.
So the plan is get the host name of the local machine, get the IPHostEntry
object for the host name retrieved and query through the address list to find the IPAddress
where AddressFamily
is InterNetwork
.
Here is the code to do that:
var ipHostEntry = Dns.GetHostEntry(Dns.GetHostName());
var ipAddressOfMachine = ipHostEntry.AddressList.FirstOrDefault(addressListItem => addressListItem.AddressFamily == AddressFamily.InterNetwork);
if (null != ipAddressOfMachine)
{
Console.WriteLine(ipAddressOfMachine.ToString());
}
Note: Dns.GetHostName()
may throw System.Net.Sockets.SocketException
is the method call will not be able to resolve the host name of the machine.
Happy Coding !!