获取服务器的所有IP

Posted on 2013-03-27 09:57  快乐的码奴  阅读(244)  评论(0)    收藏  举报
 

private string[] GetLocalIpv4()
{
//事先不知道ip的个数,数组长度未知,因此用StringCollection储存
try
{
IPAddress[] localIPs;
localIPs = Dns.GetHostAddresses(Dns.GetHostName());
StringCollection IpCollection = new StringCollection();
foreach (IPAddress ip in localIPs)
{
//根据AddressFamily判断是否为ipv4,如果是InterNetWork则为ipv6
if (ip.AddressFamily == AddressFamily.InterNetwork)
{

IpCollection.Add(ip.ToString());
}
}

string[] IpArray = new string[IpCollection.Count];
IpCollection.CopyTo(IpArray, 0);

return IpArray;
}

catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
return null;
}

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3