这是项目中的需要根据ComputerName来获取IP的一个方法,如果出现多个ComputerName,需要将多个ComputerName的字符串以“;”分开,传进方法中,然后再处理不同的Name,然后再获取不同Name的IP值,我原来的写法如下:
private static string GetIPAddressFromMachineName(string machineNames)
{
if (machineNames.Trim().EndsWith(";"))
{
machineNames = machineNames.Trim();
machineNames = machineNames.Remove(machineNames.LastIndexOf(';'), );
}
string result = "";
string[] ipadresses;
try
{
#region old
string[] machineName = machineNames.Split(';');
ipadresses = new string[machineName.Length];
for (int i = ; i < machineName.Length; i++)
{
if (machineName[i].Trim() != "")
{
IPHostEntry ipHose = Dns.GetHostEntry(machineName[i].Trim());
if (ipHose.AddressList[].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipadresses[i] = ipHose.AddressList[].ToString();
}
else if (ipHose.AddressList[].AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
ipadresses[i] = ipHose.AddressList[].ToString();
}
}
}
result = String.Join(",", ipadresses);
#endregion
} catch (Exception)
{
result = "Error";
} return result;
}
Old
我们头儿给的建议写法如下:
private static string GetIPAddressFromMachineName(string machineNames)
{
if (machineNames.Trim().EndsWith(";"))
{
machineNames = machineNames.Trim();
machineNames = machineNames.Remove(machineNames.LastIndexOf(';'), );
}
string result = "";
try
{
#region new
foreach (string machineName in machineNames.Split(";".ToArray()).ToList())
{
if (machineName.Trim() != "")
{
IPHostEntry ipHose = Dns.GetHostEntry(machineName.Trim());
if (ipHose.AddressList[].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
result += "," + ipHose.AddressList[].ToString();
}
else if(ipHose.AddressList[].AddressFamily==System.Net.Sockets.AddressFamily.InterNetworkV6)
{
result += "," + ipHose.AddressList[].ToString();
}
}
}
if (result.StartsWith(","))
{
result = result.Remove(, );
}
#endregion
} catch (Exception)
{
result = "Error";
} return result;
}
New
记录每一次的成长~~~