import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* 端口扫描工具
*
* @author czp
* @version 1.0 (2013-5-17)
*/
public class NetUtil {
private List<InetAddress> ls ;
private int port;
private Socket sc;
private String host;
private int timeOut;
public NetUtil(int port) {
this.port = port;
this.timeOut = 500;
}
public NetUtil(String baseIp,int port,int timeOut) {
this.port = port;
this.host = baseIp;
this.timeOut = timeOut;
}
/**
* 开始扫描
*/
public List<InetAddress> startScan()
{
try {
InetAddress it = null;
if(host==null)
{
it = InetAddress.getLocalHost();
}else{
it = InetAddress.getByName(host);
}
long st = System.currentTimeMillis();
sc = new Socket();
ls = new CopyOnWriteArrayList<InetAddress>();
int process = Runtime.getRuntime().availableProcessors()+1;
ExecutorService service = Executors.newFixedThreadPool(process);
String hostAddress = it.getHostAddress();
int lastIndexOf = hostAddress.lastIndexOf(".");
String start =hostAddress.substring(0, lastIndexOf+1);
int avg = 255/process;
List<Future<List<InetAddress>>> fss = new ArrayList<Future<List<InetAddress>>>();
for(int i=0;i<process;i++)
{
List<String> ipLs = new ArrayList<String>();
for (int j =(i+1)*avg; j>i*avg; j--) {
ipLs.add(start+j);
}
Future<List<InetAddress>> fs = service.submit(new ScanIp(ipLs));
fss.add(fs);
}
for (Future<List<InetAddress>> future : fss) {
ls.addAll(future.get());
}
service.shutdownNow();
System.out.println("over times is "+(System.currentTimeMillis()-st));
} catch (Exception e) {
e.printStackTrace();
}
return ls;
}
private class ScanIp implements Callable<List<InetAddress>>{
private List<String> ips;
private ScanIp(List<String> ips) {
this.ips = ips;
}
@Override
public List<InetAddress> call() throws Exception {
List<InetAddress> canReachIp = new ArrayList<InetAddress>();
for (String str : ips) {
try {
if(!Thread.interrupted())
{
InetAddress it = InetAddress.getByName(str);
InetSocketAddress endpoint = new InetSocketAddress(it.getHostAddress(),port);
sc.connect(endpoint,timeOut);
if(sc.isConnected())
{
canReachIp.add(it);
sc.close();
}
}else{
ls.addAll(canReachIp);
}
} catch (Exception e) {
}
}
return canReachIp;
}
}
public static void main(String[] args) {
System.out.println(new NetUtil("192.168.128.181",80,500).startScan());
}
}
IP 地址扫描工具
最新推荐文章于 2023-01-31 14:04:04 发布