你遇到過這種情況嗎?你的防火牆報告區域網路中的某個IP地址的電腦正在攻擊你,但是防火牆卻沒有提示發出攻擊的電腦名稱,到底誰的電腦在攻擊呢(攻擊你的電腦可能是中毒了)?有一天早上你剛剛上班,開啟電腦後發現串連不了伺服器,到伺服器那裡一看才知道,原來有人使用了伺服器的IP地址,到底誰在使用伺服器的IP地址呢?nslookup 可以實現網域名稱(主機名稱)的反查IP地址。哈哈,但今天說的是用C#實現。
1. 根據IP地址獲得主機名稱 /// <summary>
/// 根據IP地址獲得主機名稱
/// </summary>
/// <param name="ip">主機的IP地址</param>
/// <returns>主機名稱</returns>
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地址
/// <summary>
/// 根據主機名稱(網域名稱)獲得主機的IP地址
/// </summary>
/// <param name="hostName">主機名稱或網域名稱</param>
/// <example>GetIPByDomain("pc001"); GetIPByDomain("www.google.com");</example>
/// <returns>主機的IP地址</returns>
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 的功能,用於測試網路是否已經聯通 /// <summary>
/// 是否能 Ping 通指定的主機
/// </summary>
/// <param name="ip">ip 地址或主機名稱或網域名稱</param>
/// <returns>true 通,false 不通</returns>
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;
}
本文地址:http://www.cnblogs.com/anjou/archive/2007/10/11/920214.html