您的位置:首页 > 编程语言 > C#

C#获取指定IP的主机名

2011-06-19 09:56 435 查看
以下代码在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;

}

转自:http://ttgoup.blog.hexun.com/14750646_d.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: