C#實現網段掃描
2024-07-21 02:20:24
供稿:網友
摘要
想必大家對小榕時光等掃描器都非常熟悉了,有沒有自己寫一個的沖動。最近微軟推實施了.net戰略方案,c#是主推語言,你們是否有興趣用c#來實現對局域網ip地址的掃描,嘗試一下自己寫的快樂,那么請跟我來。
正文
1.先介紹一下使用的類:
dns類:在.net中的system.net命名空間下,主要的功能是從 internet 域名系統 (dns) 檢索關于特定主機的信息。
iphostentry類:將一個域名系統 (dns) 主機與一組別名和一組匹配的 ip 地址關聯,和dns類一起使用。
ipaddress 類:ip 網絡上的地址。
使用的命名空間有:
system.net 命名空間為當前網絡上使用的多種協議提供了簡單的編程接口.
system.io命名空間包含允許在數據流和文件上進行同步和異步讀取及寫入的類型。
system.thread 命名空間主要是用來多線程序編程。
程序實現以下幾個功能:
2.獲取本地主機ip地址
/// <summary>
/// 按扭查詢本機ip
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_click(object sender, system.eventargs e)
{
iphostentry myhost = new iphostentry();
try
{
this.richtextbox1.text = "";
// dns.gethostname()獲取本地計算機的主機名
// dns.gethostbyname()獲取指定 dns 主機名的 dns 信息
//得到本地主機的dns信息
myhost = dns.gethostbyname(dns.gethostname());
//顯示本地主機名
textbox1.text = myhost.hostname.tostring();
//顯示本地主機的ip地址表
for(int i=0; i<myhost.addresslist.length;i++)
{
richtextbox1.appendtext("本地主機ip地址->" + myhost.addresslist[i].tostring()+ "/r");
}
}
catch(exception error)
{
messagebox.show(error.message);
}
}
3.遠程查詢
private void button2_click(object sender, system.eventargs e)
{
this.richtextbox1.text = "";
iphostentry mydnstoip = new iphostentry();
//dns.resolve 方法: 將 dns 主機名或以點分隔的四部分表示法格式的
// ip 地址解析為 iphostentry實例
mydnstoip =dns.resolve(textbox2.text.tostring());
//顯示此域名的ip地址的列表
for(int i=0;i<mydnstoip.addresslist.length;i++)
{
richtextbox1.appendtext(textbox2.text + "的ip地址是" + mydnstoip.addresslist[i].tostring() + "/r");
}
}
4.實現網段的掃描
實現網段的掃描,確定網絡中正在使用的主機數目。這里使用了多線程技術,增加了一個線程,為了防止程序掃描的時間過長,影響程序的響應。不過在.net中由于使用了垃圾收集技術所以對線程的控制也不是很復雜的。
private void button3_click(object sender, system.eventargs e)
{
this.richtextbox1.text = "";
//thread 類: 創建并控制線程
//thread thscan = new thread(new threadstart(scantarget));
thread thscan = new thread(new threadstart(scantarget));
//thread.start 方法:啟動線程
thscan.start();
}
private void scantarget()
{
//構造ip地址的31-8bit 位,也就是固定的ip地址的前段
// numericupdown1是定義的system.windows.forms.numericupdown控件
string stripaddress = numericupdown1.text + "." + numericupdown2.text + "." + numericupdown3.text + ".";
//開始掃描地址
int nstrat = int32.parse(numericupdown4.text);
//終止掃描地址
int nend =int32.parse(numericupdown5.text);
//掃描的操作
for(int i = nstrat; i <= nend; i++)
{
string strscanipadd = stripaddress +i.tostring();
//轉換成ip地址
ipaddress myscanip = ipaddress.parse(strscanipadd);
try
{
//你可以加入自已的,增強功能
// dns.gethostbyaddress 方法: 根據 ip 地
//址獲取 dns 主機信息。
iphostentry myscanhost = dns.gethostbyaddress(myscanip);
//獲取主機的名
string strhostname =myscanhost.hostname.tostring();
richtextbox1.appendtext(strscanipadd + "->" + strhostname + "/r");
}
catch(exception error)
{
messagebox.show(error.message);
}
}
}
到此為止一個簡單用c#實現掃描器的主要功能就完成了,試一下你可以看到你的網絡上的主機,有沒有成就感了:)