Wednesday, June 16, 2010

How to get the IP address of local area connection in C#


NetworkInterface[] NInterfaces = null;
NInterfaces = NetworkInterface.GetAllNetworkInterfaces;

foreach(NetworkInterface NInterface in NInterfaces) {
if(NInterface.Name == "Local Area Connection") {
foreach(IPAddressInformation Info in NInterface.GetIPProperties().UnicastAddresses) {
if(Info.Address.AddressFamily.ToString == "InterNetwork") {
MessageBox.Show("IP Address: " + Info.Address.ToString());
}
}
}
}


You can also use this function to get the local IPv4 IP when you have IPv6 enabled:


private IPAddress GetIPAddress() {

System.Net.IPAddress IP = null;

foreach (IPAddress localIP in System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList) {
if (localIP.AddressFamily == AddressFamily.InterNetwork & IP == null) {
IP = localIP;
}
}

return IP;

}