您的位置:首页 > 其它

How to get local machine name and IP address?

2008-11-20 11:18 525 查看
THANKS nick.fletcher@iinet.net.au and Dave Sexton, your notes give me a lot of help.

Environment.MachineName will return the local NetBios name as a string

you can also use:

System.Net.dns.GetHostName();

Getting the IP addresses is a little more tricky - as there can be more
than one per host name:

public static class Network

{

public static string GetMachineName()

{

//get domain and machine name;

//return System.Net.Dns.GetHostName();

//just get the local machine's NetBIOS name.

return Environment.MachineName;

}

public static string GetUserName()

{

return HttpContext.Current.User.Identity.Name;

}

#region DNS

public static IPAddress FindIPAddress(bool localPreference)

{

return FindIPAddress(Dns.GetHostEntry(Dns.GetHostName()),

localPreference);

}

public static IPAddress FindIPAddress(IPHostEntry host, bool

localPreference)

{

if (host == null)

throw new ArgumentNullException("host");

if (host.AddressList.Length == 1)

return host.AddressList[0];

else

{

foreach (System.Net.IPAddress address in host.AddressList)

{

bool local = IsLocal(address);

if (local && localPreference)

return address;

else if (!local && !localPreference)

return address;

}

return host.AddressList[0];

}

}

public static bool IsLocal(IPAddress address)

{

if (address == null)

throw new ArgumentNullException("address");

byte[] addr = address.GetAddressBytes();

return addr[0] == 10

|| (addr[0] == 192 && addr[1] == 168)

|| (addr[0] == 172 && addr[1] >= 16 && addr[1] <= 31);

}

#endregion

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐