java编写一个基于Socket的扫描程序,识别局域网内活跃主机

与每一台计算机的TCP 135号端口建立连接。如果建立连接成功,那么就表明该设备已经开启Windows系统,是一个活跃主机。

多线程,动态扫描,即不规定IP地址,直接通过本机IP地址和本机子网掩码编程自动计算整个局域网其他主机号,依次扫描。

获取本机IP的方法:

InetAddress.getLocalHost().getHostAddress();

得到本机IP后,获取IP网络号部分的长度

List<InterfaceAddress> list=networkInterface.getInterfaceAddresses();
		int netLength=list.get(0).getNetworkPrefixLength();
		System.out.println("网络号长度:"+netLength);

由此可计算局域网子网内所有IP地址

for(int i=1;i<Math.pow(2,hostLength)-1;i++)
		{
			String str="00000000";
			String temp;
			temp=str+Integer.toBinaryString(i);
			allIp[i-1]=netPart+temp.substring(temp.length()-8);
			allIp[i-1]=Integer.parseInt(
					allIp[i-1].substring(0, 8), 2)+"."+
					Integer.parseInt(allIp[i-1].substring(8, 16), 2)+"."+
					Integer.parseInt(allIp[i-1].substring(16, 24), 2)+"."+
					Integer.parseInt(allIp[i-1].substring(24), 2
			);	
		}

获取子网所有IP后,Socket扫描相应主机135号端口,未抛出异常即连接成功

try {	
				Socket sock = null;
				sock = new Socket(allIp,135);
				System.out.println("connected "+allIp+"\n");
				sock.close();
				
			} catch (IOException e) {
	        	System.out.println("not connected "+allIp+"\n");
			}

java多线程的调用方法

int threadNum=50;
		ThreadPoolExecutor executor = new ThreadPoolExecutor(2, threadNum, 300,
	                TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(3),
	                new ThreadPoolExecutor.CallerRunsPolicy());
	    for (int i = 0; i < threadNum; i++) {
	    	for(int j=0;j<allIp.length;j++){
	            executor.execute(new UsesSocket(allIp[j]));
	        }
	    	executor.shutdown();
	    }

以下是完整的代码:
test.java

package test;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test {
	
	
	public static void main(String[] agrs) throws UnknownHostException
	{
		String ip=null;
		InetAddress localHost = null;
		
		//获取本机ip
		try {
			localHost = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			
			e.printStackTrace();
		} 
		
		ip=localHost.getHostAddress();
		System.out.println("本机ip:"+ip);
		
		NetworkInterface networkInterface = null;
		try {
			networkInterface = NetworkInterface.getByInetAddress(localHost);
			
		} catch (SocketException e) {
			e.printStackTrace();
		} 
		
		
		//获取ip网络号部分长度
		List<InterfaceAddress> list=networkInterface.getInterfaceAddresses();
		int netLength=list.get(0).getNetworkPrefixLength();
		System.out.println("网络号长度:"+netLength);
		
		String[] allIp=AllSubnetIp(ip,netLength);
		//UsesSocket(allIp);
		
		//多线程同时扫描
		int threadNum=50;
		ThreadPoolExecutor executor = new ThreadPoolExecutor(2, threadNum, 300,
	                TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(3),
	                new ThreadPoolExecutor.CallerRunsPolicy());
	    for (int i = 0; i < threadNum; i++) {
	    	for(int j=0;j<allIp.length;j++){
	            executor.execute(new UsesSocket(allIp[j]));
	        }
	    	executor.shutdown();
	    }
	    
	}

	 //计算子网内所有ip
	public static String[] AllSubnetIp(String localIp,int netLength)
	{
		int hostLength=32-netLength;
		String[] allIp = new String[(int) (Math.pow(2, hostLength)-2)];
		
		String[] splitedIp=null;
		int[] ipToInt = new int[4];
		
		splitedIp=localIp.split("\\."); // . 表示任意字符,要写成 " \\. "
		for(int i=0;i<splitedIp.length;i++)
		{
			ipToInt[i]=Integer.parseInt(splitedIp[i]);//转化成int
			//System.out.println(ipToInt[i]);
		}	
		String s="";
		
		for(int i=0;i<ipToInt.length;i++)
		{
			String str="00000000";
			String temp;
			temp=str+Integer.toBinaryString(ipToInt[i]);
			//本机ip的二进制表示
			s=s+temp.substring(temp.length()-8);
		
		}
		System.out.println("本机IP的二进制表示:"+s+"   "+s.length()+"\n");
		
		//截取出不变的网络号部分
		String netPart;
		netPart=s.substring(0, netLength);

		for(int i=1;i<Math.pow(2,hostLength)-1;i++)
		{
			String str="00000000";
			String temp;
			temp=str+Integer.toBinaryString(i);
			allIp[i-1]=netPart+temp.substring(temp.length()-8);
			allIp[i-1]=Integer.parseInt(
					allIp[i-1].substring(0, 8), 2)+"."+
					Integer.parseInt(allIp[i-1].substring(8, 16), 2)+"."+
					Integer.parseInt(allIp[i-1].substring(16, 24), 2)+"."+
					Integer.parseInt(allIp[i-1].substring(24), 2
			);	
		}
		return allIp;
	}
}

UsesSocket.java

package test;

import java.io.IOException;
import java.net.Socket;

public class UsesSocket implements Runnable{

	String allIp;
	UsesSocket(String allIp)
	{
		this.allIp=allIp;
	}

	@Override
	public void run() {
		
			try {	
				Socket sock = null;
				sock = new Socket(allIp,135);
				System.out.println("connected "+allIp+"\n");
				sock.close();
				
			} catch (IOException e) {
	        	System.out.println("not connected "+allIp+"\n");
			}	
	}
}

发布了4 篇原创文章 · 获赞 2 · 访问量 56

猜你喜欢

转载自blog.csdn.net/qq_45014208/article/details/103989327
今日推荐