一个简单的利用线程池技术实现端口扫描(tcp)的小程序:
关键代码如下:
// 扫描本机
private void getlocal()
{
string ip = getip();
string portstart = txportstart1.gettext().trim();
string portend = txportend1.gettext().trim();
if (portstart.length() == 0 || portend.length() == 0)
return;
int s = 0;
int e = 0;
try {
s = integer.valueof(portstart);
e = integer.valueof(portend);
} catch (exception ex) {
joptionpane.showmessagedialog(null, "端口输入有误");
return;
}
// 检查端口是否超出范围
if (! (checkport(s) && checkport(e)))
{
joptionpane.showmessagedialog(null, "端口应该大于0而小于65535");
return;
}
scann(ip, s, e);
runthread(); // 启动线程, 监视扫描是否已完成
}
private string getip()
{
try {
inetaddress addr = inetaddress.getlocalhost();
return addr.gethostaddress().tostring(); // ip
}
catch (exception e)
{
joptionpane.showmessagedialog(null, "获取ip出错!");
}
return null;
}
// 扫描单个ip
private void scann(string ip, int startport, int endport)
{
// 将所有按钮设为不可用
setbtnedit(false);
status.settext("请稍候...");
string[] add = {ip, ""};
table.addrow(add);
exec = executors.newfixedthreadpool(10);
for (int i = startport; i <= endport; i++)
exec.execute(new runsocket(ip, i));
exec.shutdown();
}
|