在C#中,获取IP的有效方法有以下几种:
- 使用Dns类的GetHostAddresses方法来获取本地主机的IP地址:
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { Console.WriteLine(ip.ToString()); }
- 使用System.Net.NetworkInformation命名空间下的NetworkInterface类来获取本地网络接口的IP地址:
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in interfaces) { IPInterfaceProperties properties = adapter.GetIPProperties(); foreach (UnicastIPAddressInformation uniAddress in properties.UnicastAddresses) { Console.WriteLine(uniAddress.Address.ToString()); } }
- 使用System.Net.Sockets命名空间下的Socket类来获取指定主机的IP地址:
IPAddress[] addresses = Dns.GetHostAddresses("www.example.com"); foreach (IPAddress address in addresses) { Console.WriteLine(address.ToString()); }
这些方法可以根据具体的需求选择合适的方式来获取IP地址。