java实现端口扫描
温馨提示:
本文最后更新于 2022年04月04日,已超过 992 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
实现原理
通过能否正常建立socket连接,来判断端口是否开启。
输入需要扫描的端口范围,通过开启多线程来实现快速扫描。
代码实现
package com.it1997;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class PortScaner {
public static void main(String[] args) throws InterruptedException {
String host = "it1997.com";
int startPort =1;
int endPort = 10000;
int step = Math.round(endPort/500)+1;
for(int i=1;i<step;i++){
int start = startPort+(i-1)*500;
int end = startPort+i*500;
System.out.println("正在扫描"+start+"-"+end);
SP(host,start,end);
}
}
public static void SP(String host,int startPort,int endPort) throws InterruptedException {
List<Integer> portList = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(endPort-startPort+1);
for (int port = startPort; port <= endPort; port++) {
int finalPort = port;
//System.out.println(port);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(host, finalPort));
System.out.println("端口" + finalPort + "开放");
portList.add(finalPort);
} catch (Exception e) {
//e.printStackTrace();
// System.out.println("端口" + finalPort + "未开放");
}
latch.countDown();
}
});
thread.start();
}
latch.await();
portList.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
}
}
正文到此结束
- 本文标签: Java
- 本文链接: https://www.it1997.com/article/43
- 版权声明: 本文由小陈没烦恼原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权