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
}
本文介绍了一种方法来获取当前计算机的NetBIOS名称及IP地址。通过使用Environment.MachineName可以得到本地主机名,而通过Dns.GetHostEntry结合Dns.GetHostName则能够获取到所有分配给该主机的IP地址。文章还提供了一个实用类Network,其中包含用于查找特定偏好设置下的IP地址的方法。
511

被折叠的 条评论
为什么被折叠?



