一、新建項目
新建---->文件----->項目------>windows窗體應用程序----->scan.sln
二、設計界面
三、寫代碼
四、最后效果
1、打開虛擬機---->windowserver2003---->cmd---->ipconfig
得到ip地址192.168.67.131
2、輸入:
3、在2003里輸入
netstat -an -p tcp ? 可看到掃到1000以內的端口開放結果相同
【scan.exe】
源代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;//通信相關都會用到的命名空間
using System.Threading;//子線程
//using System.Diagnostics;
namespace scan
{
public partial class Form1 : Form
{
string addr = "";//放ip地址
int port;//放端口號
Thread scanthread;//定義一個子線程
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
//子進程要使用父進程的控件時,要加這一句
}
private void button1_Click(object sender, EventArgs e)//掃描按鈕
{
//創建主進程,從portscan函數開始執行
Thread process = new Thread(new ThreadStart(portscan));
process.Start();//啟動進程
progressBar1.Minimum = 0;//最小值
progressBar1.Maximum = 1000;//最大值
listBox1.Items.Clear();//列表.項.清空
listBox1.Items.Add("掃描器v1.0");
listBox1.Items.Add("");//加空行
}
private void portscan()//一個進程分配為1000個子線程
{
listBox1.Items.Add("開始掃描,可能要等幾分鐘");
addr = textBox1.Text;//取出ip地址
for(int i=1;i<=1000;i++)//創建1000個子線程
{
port = i;
scanthread = new Thread(new ThreadStart(scan));
scanthread.Start();
System.Threading.Thread.Sleep(10);//每隔10ms,啟動一個子線程
label2.Text = port.ToString();//label2提示當前掃描到哪個端口號了;port轉換成字符串了
progressBar1.Value = port;//進度條
}
}
private void scan()
{
int i = port;
TcpClient myclient = null;
try//如果執行try子句出錯,就跳到catch執行;正確則順利執行
{
myclient = new TcpClient();
myclient.Connect(addr, port);//端口連接
listBox1.Items.Add("端口" + port.ToString() + "開放");
}
catch
{
if(i==1000)
{
listBox1.Items.Add("掃描結束!");
}
}
}
private void button2_Click(object sender, EventArgs e)//退出按鈕
{
System.Environment.Exit(0);//父進程和子進程都退出
}
}
}