读书人

C# 在局域网里根据IP获取对应计算机名

发布时间: 2013-10-21 17:02:52 作者: rapoo

C# 在局域网里根据IP获取对应计算机名字

string computername= Dns.GetHostEntry(textBox1.Text).HostName;//textBox1.Text写入自己的IP

或者 string computername= Dns.GetHostEntry(“”).HostName 能够获取到自己电脑的名字

可是现在我要获取局域网的计算机的名字,所有IP已获取了,可是不行,哪位高手指点一下,因为我要同时显示IP和计算机的名字,如果单独获取计算机的名字也实现了。现在就是要输入一个IP就能得到计算机的名字。

C#的局域网扫描工具
http://www.codeproject.com/KB/cs/c__ip_scanner.aspx
[解决办法]
遍历局域网获取IP和HostName的方法


void Find( ) //
{
Add( "-- >>> >> >>> Found station <<< << <<< -- " );
int lastF = ipFrom.Text.LastIndexOf(".");
int lastT = ipTo.Text.LastIndexOf(".");
string frm = ipFrom.Text.Substring(lastF+1);
string tto = ipTo.Text.Substring(lastT+1);
int result = 0;
System.Diagnostics.Debug.WriteLine( frm + " " + tto);
for( int i = int.Parse( frm); i <= int.Parse(tto );i++)
{
try
{
string address = ipTo.Text.Substring(0,lastT+1);
System.Diagnostics.Debug.WriteLine(ipTo.Text.Substring(0,lastT+1)+i);
IPHostEntry he = Dns.GetHostByAddress( address+i);
Add( he.HostName );
result += 1;
}

catch( SocketException )
{
// in cazul unei erori
}
catch( Exception )
{
// previne bloacarea programului
}
}

}


[解决办法]
引用:
唉 大家好,好几天没有上网,才看见,你们理解有误呀,我是说已经获得到了IP,要获取该IP的计算机的名字。


你是要遍历IP数组列表获取计算机的名字还是输入一个IP获得一台计算机的名字?

根据输入的ip获取计算机名字:
Dns.GetHostByAddress(IP地址).HostName.ToString()


如果要根据你获取的IP数组遍历计算机名:
for (int i=0;i<list.Length;i++)
{
Dns.GetHostByAddress(list[i]).HostName.ToString()


}

读书人网 >C#

热点推荐