11.5 Get the IP Address of the Current Computer


Problem

You need to retrieve the IP address of the current computer, perhaps to use later in networking code.

Solution

Use the System.Net.Dns class, which provides static GetHostName and GetHostByName methods .

Discussion

The Dns class provides domain name resolution services. You can invoke its GetHostName to retrieve the host name for the current computer. You can then translate the host name into an IP address using GetHostByName . Here's an example:

 using System; using System.Net; public class GetIPAddress {     private static void Main() {         // Look up the host name and IP address.         string hostName = Dns.GetHostName();         // Get the first matching IP address.         string ipAddress =            Dns.GetHostByName(hostName).AddressList[0].ToString();         Console.WriteLine("Host name: " + hostName);         Console.WriteLine("IP address: " + ipAddress);         Console.ReadLine();     } } 

Be aware that the GetHostByName method returns a list of usable IP addresses. In many cases, this address list will contain only one entry.

If you run this code, you'll see something like this

 Host name: fariamat IP address: 24.114.131.70 
Note  

When using IP addresses in network communication, you can always use the loopback address 127.0.0.1 to refer to the current computer, instead of its machine-specific IP address.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net