在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地址。