I have this method for getting IP v4 of an IIS server by its computer name, every time I run this function, it gives me the different result (it alternate between 4 different IP addresses, three of them are in the same range and one is in range 192.168.x.x)
public static string GetIpFromPcName(string PcName = null)
{
try
{
// in order to get ip v4 address
// look here: https://stackoverflow.com/questions/6668810/how-do-i-determine-the-local-host-s-ipv4-addresses
// can a pc have multiple ips?
if (string.IsNullOrEmpty(PcName))
return null;
string IP4Address = String.Empty;
var hostEntry = Dns.GetHostEntry(PcName);
var ipaddresses = Dns.GetHostAddresses(PcName);
Console.WriteLine("HostName: {0}", hostEntry.HostName);
Console.WriteLine("Aliases:");
foreach (var entry in hostEntry.Aliases)
{
Console.WriteLine("\t{0}", entry);
}
Console.WriteLine("Addresslist: ");
foreach (var entry in hostEntry.AddressList)
{
Console.WriteLine("\t{0}", entry.ToString());
}
foreach (IPAddress IPA in Dns.GetHostAddresses(PcName))
{
if (IPA.AddressFamily == AddressFamily.InterNetwork)
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
catch (Exception ex)
{
Console.WriteLine("Error in getting ip address for {0}", PcName);
return null;
}
}
Also, one strange thing that I observed is that what gets printed for Addresslist
is different from the final return value of the function.
The question is...
why I'm getting different results every time?