一个简单的利用线程池技术实现端口扫描(TCP)的小程序
关键代码如下
// 扫描本机
private void getLocal()
{
String ip = getIP();
String portStart = txPortStartgetText()trim();
String portEnd = txPortEndgetText()trim();
if (portStartlength() == || portEndlength() == )
return;
int s = ;
int e = ;
try {
s = IntegervalueOf(portStart);
e = IntegervalueOf(portEnd);
} catch (Exception ex) {
JOptionPaneshowMessageDialog(null 端口输入有误);
return;
}
// 检查端口是否超出范围
if (! (checkPort(s) && checkPort(e)))
{
JOptionPaneshowMessageDialog(null 端口应该大于而小于);
return;
}
scann(ip s e);
runThread(); // 启动线程 监视扫描是否已完成
}
private String getIP()
{
try {
InetAddress addr = InetAddressgetLocalHost();
return addrgetHostAddress()toString(); // ip
}
catch (Exception e)
{
JOptionPaneshowMessageDialog(null 获取IP出错!);
}
return null;
}
// 扫描单个IP
private void scann(String ip int startPort int endPort)
{
// 将所有按钮设为不可用
setBtnEdit(false);
statussetText(请稍候);
String[] add = {ip };
tableaddRow(add);
exec = ExecutorsnewFixedThreadPool();
for (int i = startPort; i <= endPort; i++)
execexecute(new RunSocket(ip i));
execshutdown();
}