1
public static string GetLocalIpAddress()
    {
        string hostName = Dns.GetHostName();
        IPHostEntry ip = Dns.GetHostEntry(hostName);
        string IpAddress = Convert.ToString(ip.AddressList[2]);
        return IpAddress.ToString();
    }

This will some times show Index out of bound exception what should be the problem in it.? thanks in advance

Assassino
  • 31
  • 1
  • 3
  • 11

3 Answers3

7

try this method, it works for me.

 public static string GetIPAddress()
    {
        IPHostEntry host;
        string localIP = "?";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localIP = ip.ToString();
            }
        }
        return localIP;
    }

Thanks,

Mohd
  • 71
  • 1
  • 3
1
foreach (var addr in Dns.GetHostEntry(string.Empty).AddressList)
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
Console.WriteLine("IPv4 Address: {0}", addr)
}
0

As they have answering before. You should check your lenght on the AddressList. Becouse it will not always be 2.

Here you have another answer on stackoverflow: Getting valid IP from IPHostEntry

Community
  • 1
  • 1
sn1ckers
  • 103
  • 7