Public Static String Getlocalip ()
{
Try
{
String Hostname = DNS. gethostname (); // Get the Host Name
Iphostentry ipentry = DNS. gethostentry (hostname );
For ( Int I = 0 ; I <ipentry. Addresslist. length; I ++)
{
// Select an IPv4 IP address from the IP address list.
// Addressfamily. Internetwork indicates that the IP address is IPv4,
// Addressfamily. internetworkv6 indicates that this address is of the IPv6 type.
If (Ipentry. Addresslist [I]. addressfamily = addressfamily. InterNetwork)
{
Return Ipentry. Addresslist [I]. tostring ();
}
}
Return "" ;
}
Catch (Exception ex)
{
MessageBox. Show ( " An error occurred while obtaining the local IP Address: " + Ex. Message );
Return "" ;
}
}
C # when obtaining the IP address of the local machine, it is possible to return an IPv6 address. To obtain an IPv4 address correctly, we need to use addressfamily, after one-by-one comparison, you can obtain the IPv4 address of the local machine.