获得iP
如何通过c#获得局域网内其他电脑的ip位址 问题点数:0、回复次数:7Top
1 楼pdsinfo(新手)回复于 2003-05-04 08:51:27 得分 0
GetHostByNameTop
2 楼zjwuweim(冰火)回复于 2003-05-04 10:01:59 得分 0
public string LocalIpAdress()
{
try
{
IPHostEntry iph = new IPHostEntry();
iph=Dns.GetHostByName(Dns.GetHostName());
return iph.AddressList[0].ToString();
}
catch(Exception se)
{
throw new Exception(se.Message);
}
}
Top
3 楼csharp33(雪桐)回复于 2003-05-04 10:53:36 得分 0
损不损呀你Top
4 楼smart(smart)回复于 2003-05-04 13:28:35 得分 0
iph.AddressList[0].ToString()是第一個ip位址
那其他的是不是 AddressList[1]等Top
5 楼newpant(Fly)回复于 2003-05-04 15:11:48 得分 0
得到一个局域网段内所有在线机器的IP及主机名,我的思路是先得到自己的IP,比如211.68.46.5,这个网段就是211.68.46.0--211.68.46.255,分别用Dns.GetHostByAddress来取得主机(返回IPHostEntry),如果解析成功,就会得到一个IPHostEntry的实例,不成功就会引发SocketException错误.之后再把信息放在ListBox中
代码如下:
private void SearchIP_Thread()
{
IPHostEntry ipHost=Dns.GetHostByName(Dns.GetHostName());
myIP=ipHost.AddressList[0].ToString();
myIP=myIP.Remove(myIP.LastIndexOf(".")+1,myIP.Length-myIP.LastIndexOf(".")-1);
for(int i=0;i<256;i++)
{
try
{
IPHostEntry eachIP=Dns.GetHostByAddress(myIP+i.ToString());
listBox1.Items.Add("IP地址: "+myIP+i.ToString()+" 主机名为: "+eachIP.HostName.ToString()+"\r\n");
}
catch(SocketException exp)
{
listBox1.Items.Add("IP地址: "+myIP+i.ToString()+" 解析错误,可能是主机不在线");
}
}
}
至于启动这段代码,最好是放在一个线程(Thread)中,不然,用户界面会停止响应
我把启动放在了Form_Load中
private void Form4_Load(object sender, System.EventArgs e)
{
Thread SearchIP=new Thread(new ThreadStart(this.SearchIP_Thread));
SearchIP.Start();
}
注意要引用
using System.Net;
using System.Net.Sockets;
using System.Threading;Top
6 楼smart(smart)回复于 2003-05-06 09:32:15 得分 0
哪有關於IPAdress相關類的資料看Top




