在C#中,获取IP的有效方法有以下几种:
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
Console.WriteLine(ip.ToString());
}
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in interfaces)
{
IPInterfaceProperties properties = adapter.GetIPProperties();
foreach (UnicastIPAddressInformation uniAddress in properties.UnicastAddresses)
{
Console.WriteLine(uniAddress.Address.ToString());
}
}
IPAddress[] addresses = Dns.GetHostAddresses("www.example.com");
foreach (IPAddress address in addresses)
{
Console.WriteLine(address.ToString());
}
这些方法可以根据具体的需求选择合适的方式来获取IP地址。