1. 根据IP地址获得主机名称 复制 保存/// /// 根据IP地址获得主机名称/// /// 主机的IP地址/// 主机名称public string GetHostNameByIp(string ip){ ip = ip.Trim(); if (ip == string.Empty) return string.Empty; try { // 是否 Ping 的通 if (this.Ping(ip)) { System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(ip); return host.HostName; } else return string.Empty; } catch (Exception) { return string.Empty; }}说明:如果你的电脑可以上网你甚至可以查询到:IP地址“64.233.189.104”是 Google 的一个名为“hk-in-f104.google.com”的主机的IP地址。 关于代码中 this.Ping(ip) 方法后面再说。 既然说了如何“根据IP地址获得主机名称”,那就要再说说如何“根据主机名获得主机的IP地址”吧。 2. 根据主机名获得主机的IP地址 复制 保存/// /// 根据主机名(域名)获得主机的IP地址/// /// 主机名或域名/// GetIPByDomain("pc001"); GetIPByDomain(" www.google.com");/// 主机的IP地址public string GetIpByHostName(string hostName){ hostName = hostName.Trim(); if (hostName == string.Empty) return string.Empty; try { System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(hostName); return host.AddressList.GetValue(0).ToString(); } catch (Exception) { return string.Empty; }}说明:如果你的电脑可以上网你甚至可以查询到:“ www.google.com”的IP地址是“64.233.189.104”。 最后,再说说C#实现简单的 Ping 的功能,用于测试网络是否已经联通。 3. C#实现简单的 Ping 的功能,用于测试网络是否已经联通 复制 保存/// /// 是否能 Ping 通指定的主机/// /// ip 地址或主机名或域名/// true 通,false 不通public bool Ping(string ip){ System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; string data = "Test Data!"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 1000; // Timeout 时间,单位:毫秒 System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) return true; else return false;}
很简单
方法1:网上下载一个 局域网查看工具,局域网内IP机器对应的主机一目了然。
方法2:直接在路由上面也能看到IP对应的主机
nbtstat -a IP