Public static string getlocalip ()
{
Try
{
String hostname = DNS. gethostname (); // obtain the host name.
Iphostentry ipentry = DNS. gethostentry (hostname );
For (INT I = 0; I <ipentry. Addresslist. length; I ++)
{
// Filter IPv4 IP addresses from the IP address list
// Addressfamily. Internetwork indicates that the IP address is IPv4,
// Addressfamily. internetworkv6 indicates that the 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.