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;

}

1 comments:

Andrea from Milano said...

Thanks a lot. Concise and effective.
This is the porting to VB.net:
Dim strIPV4 As String = String.Empty
Dim strIPV6 As String = String.Empty
Dim strIndirizzoMAC As String = String.Empty
Dim InterfacceDiRete() As Net.NetworkInformation.NetworkInterface = Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
For Each InterfacciaCorrente As Net.NetworkInformation.NetworkInterface In InterfacceDiRete
If InterfacciaCorrente.Name.StartsWith("Local Area Connection") Then
strIndirizzoMAC = InterfacciaCorrente.GetPhysicalAddress().ToString()
MsgBox(strIndirizzoMAC)
For Each Info As Net.NetworkInformation.IPAddressInformation In InterfacciaCorrente.GetIPProperties.UnicastAddresses
If Info.Address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
strIPV4 = Info.Address.ToString
MsgBox("IpV4 = " & strIPV4)
End If
If Info.Address.AddressFamily = Net.Sockets.AddressFamily.InterNetworkV6 Then
strIPV6 = Info.Address.ToString
MsgBox("IpV6 = " & strIPV6)
End If
Next
End If
Next

Post a Comment