我想创建主机名到IP地址,反之亦然。但是我遇到一个问题,其中1个主机名返回2个IP地址,而当我将IP地址重新转换为主机名时,只有其中一个返回正确的主机名。
转换CEGN5CG7260FR7.xxxxx.xxx
的示例将返回192.168.X.XX
和10.132.XXX.XXX
,但是当重新转换回主机名时,只有10.132.XXX.XXX
返回正确的主机名。
此代码片段用于将主机名转换为IP地址:-
// Convert hostname to IP address
IPHostEntry host = Dns.GetHostEntry(hostList[i]);
IPAddress[] ipaddr = host.AddressList;
// Loop through the IP Address array and add the IP address to IP List
foreach (IPAddress addr in ipaddr)
{
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipList.Add(addr.ToString());
}
}
// Display items in IP Address textbox
foreach (var ip in ipList)
{
ips += ip + Environment.NewLine;
}
txtIP.Text = ips;
此代码片段用于将IP地址转换为主机名:-
// Convert IP address to hostname
IPHostEntry IP = Dns.GetHostEntry(IPAddress.Parse(ip));
if (IP != null)
{
hostList.Add(IP.HostName);
}
// Display items in Hostname textbox
foreach (var hn in hostList)
{
hosts += hn + Environment.NewLine;
}
txtHost.Text = hosts;
我只能获得并显示10.132.XXX.XXX
IP地址而忽略第一个IP地址,该怎么办?
答案 0 :(得分:2)
您可以尝试使用此代码找到正确的IP地址。
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}