Search code examples
c#.net.net-3.5ip-address

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?


Solution

  • In How to get IP addresses in .NET with a host name by John Spano, it says to add the System.Net namespace, and use the following code:

    //To get the local IP address 
    string sHostName = Dns.GetHostName (); 
    IPHostEntry ipE = Dns.GetHostByName (sHostName); 
    IPAddress [] IpA = ipE.AddressList; 
    for (int i = 0; i < IpA.Length; i++) 
    { 
        Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ()); 
    }