C#获取指定IP的主机名
以下代码在visiual studio 2003下调试通过。
方法一:使用GetHostByAddress函数
string mystartIP = "222.206.84."; // IP地址
string myip;
int s;
string name;
for(s = 1; s <= 125; s++) //IP地址开始和结束
{
myip = mystartIP + s.ToString();
//转换IP地址
IPAddress myscanip = IPAddress.Parse(myip);
try
{
IPHostEntry myscanhost = Dns.GetHostByAddress(myscanip);
name = myscanhost.HostName.ToString();
this.listBox1.Items.Add(myip + " " + name);
}
catch
{
}
方法二:开启进程,调用nbtstat命令,通过分析该命令的执行结果获得指定IP的主机名。
public static string GetRemoteHostByNetBIOS(string clientIP)
{
string ip = clientIP;
string dirResults = "";
char[] hostResult;
string Result;
ProcessStartInfo psi = new ProcessStartInfo();
Process proc = new Process();
psi.FileName = "nbtstat.exe";
psi.Arguments = "-A " + ip;
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.RedirectStandardError = true;
proc = Process.Start(psi);
dirResults = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
hostResult = new char[(dirResults.IndexOf("<")-dirResults.IndexOf("-/r/r/n")-8)]; //后面4个空格加4个"-/r/r/n"字符
dirResults.CopyTo(dirResults.IndexOf("-/r/r/n") + 8, hostResult, 0, dirResults.IndexOf("<") - dirResults.IndexOf("-/r/r/n") - 8);
Result = new string(hostResult);
return Result;
}