我有以下代码:
Dim ipAdd As IPAddress = Dns.GetHostEntry(strHostname).AddressList(0)
Dim strIP As String = ipAdd.ToString()
当我转换为String而不是像192.168.1.0或类似的IPv4地址时,我得到IPv6版本:fd80 :: 5dbe:5d89:e51b:d313地址。
有没有办法可以从IPAddress类型返回IPv4地址?
由于
答案 0 :(得分:15)
您可以获取第一个IPv4地址,而不是无条件地获取AddressList的第一个元素:
var address = Dns.GetHostEntry(strHostname)
.AddressList
.First(ip => ip.AddressFamily == AddressFamily.InterNetwork);
答案 1 :(得分:2)
dtb的解决方案适用于许多情况。但是,在许多情况下,用户可能在其系统上设置了多个v4 IP。有时这是因为它们有一些“虚拟”适配器(来自VirtualBox或VMWare等应用程序),或者因为它们有多个物理网络适配器连接到它们的计算机。
不言而喻,在这些情况下,使用正确的IP非常重要。您可能需要考虑询问用户哪个IP适当。
要获取可用的v4 IP列表,您可以使用类似于以下代码:
'获取包含所有可用IP的数组: Dim IPList()As IPAddress = Net.Dns.GetHostEntry(Net.Dns.GetHostName.ToString).AddressList
'Copy valid IPs from IPList to FinalIPList
Dim FinalIPList As New ArrayList(IPList.Length)
For Each IP As IPAddress In IPList
'We want to keep IPs only if they are IPv4 and not a 'LoopBack' device
'(an InterNetwork AddressFamily indicates a v4 IP)
If ((Not IPAddress.IsLoopback(IP)) And (IP.AddressFamily = AddressFamily.InterNetwork)) Then
FinalIPList.Add(IP)
End If
Next IP
答案 2 :(得分:0)
对我来说,解决方案是" First"谓词不能正常工作,这是适合我的代码:
public static string GetLocalIP()
{
string ipv4Address = String.Empty;
foreach (IPAddress currrentIPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (currrentIPAddress.AddressFamily.ToString() == System.Net.Sockets.AddressFamily.InterNetwork.ToString())
{
ipv4Address = currrentIPAddress.ToString();
break;
}
}
return ipv4Address;
}