1. 程式人生 > >得到區域網下裝置機的ip和hostname

得到區域網下裝置機的ip和hostname

要得到同一區域網下的主機的ip和主機名,有兩種方式。

第一種一種是通過執行shell操作ping 出主機名

原理是,區域網中ip段就最後一位不同,如192.168.0.1與192.168.0.12屬於同一區域網內

需要遍歷區域網IP的,大體分為兩步::
1.得到區域網網段,可由自己機器的IP來確定
2.根據IP型別,一次遍歷區域網內IP地址(遍歷0---255)

這個通過通過執行ping命令實現(ping 192.168.0.1),但是這個過程執行255次,會很慢,通過多執行緒實現

 class LanPing

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class LanPing {
	private int corePoolSize;//執行緒池的執行緒個數
	private int maximumPoolSize;
	private ThreadPoolExecutor threadPool;
	private List<DeviceInfo> devices; //用於儲存每次ping執行緒執行通過的的結果ip+hostName;
	public LanPing() {
		corePoolSize=5;
		maximumPoolSize=100;
		threadPool=new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 3, 
				TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10),
				new ThreadPoolExecutor.CallerRunsPolicy());
		devices=new ArrayList<DeviceInfo>();
	}
	public List<DeviceInfo> search() throws UnknownHostException, InterruptedException{
		InetAddress host = InetAddress.getLocalHost();
    	String hostName=host.getHostName();
    	String hostAddress = host.getHostAddress();
    	System.out.println(hostName+":"+hostAddress);
    	int k=0;
    	k=hostAddress.lastIndexOf(".");
    	String ss = hostAddress.substring(0,k+1);
    	for(int i=1;i <255;i++){  //對所有區域網Ip
    	  String iip=ss+i;
    	  threadPool.execute(new PingIP(iip));
    	  Thread.sleep(100);
    	}
    	return devices;
	}
    
	
	
    class  PingIP implements Runnable{
    	private String ip;
    	public PingIP(String ip) {
    		this.ip=ip;
		}
        synchronized public void  run(){
    		try{
	    		String ping="ping -n 1 -w 5 "+ip;
	        	System.out.println(ping);
	        	Process process=Runtime.getRuntime().exec(ping);
	        	InputStreamReader inputStream = new InputStreamReader(process.getInputStream(),"GBK");
	        	BufferedReader reader=new BufferedReader(inputStream);
	        	StringBuffer buf=new StringBuffer();
	        	String s;
	        	while((s=reader.readLine())!=null){
	        		buf.append(s+"\n");
	        	}
	            if(buf.toString().indexOf("請求超時")!=-1){
	            	
	            }else{
	            	InetAddress host = InetAddress.getByName(ip);
	            	String hostName=host.getHostName();
	            	DeviceInfo deviceInfo=new DeviceInfo(hostName, ip);
	            	devices.add(deviceInfo);
	            	System.out.println(hostName+":"+ip);
	            }
	        	//System.out.println(buf.toString());
    		}catch(IOException e){
    			e.printStackTrace();
    		}
    	}
    }
    class DeviceInfo{
    	private String name;
    	private String ip;
    	public DeviceInfo(String name,String ip) {
    		this.name=name;
    		this.ip=ip;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getIp() {
			return ip;
		}
		public void setIp(String ip) {
			this.ip = ip;
		}
    }
}
測試執行
 LanPing lanPing=new LanPing();
        try {
        	List<LanPing.DeviceInfo> infos=lanPing.search();
        	for(LanPing.DeviceInfo info:infos){
        		System.out.println(info.getName()+":"+info.getIp());
        		
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}


第二種是在區域網中每臺主機安裝服務端監聽程式,然後通過一臺裝置廣播,得到所有裝置資訊,缺點是事前得先在區域網中每臺裝置安裝

伺服器端   

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;


public class ControllerServer {
    private int port;
    private final int DATA_LENGTH=1024*4;
    MouseController controller;
    public ControllerServer(int port) throws IOException {
    	this.port=port;
	}
    public void service() throws IOException{
       byte[] inBuf=new byte[DATA_LENGTH]; //接收緩衝
 	   DatagramPacket inPacket=new DatagramPacket(inBuf, DATA_LENGTH);//接收資料包
 	   DatagramPacket outPacket=null;//傳送資料包
 	   DatagramSocket socket=null;
	   socket = new DatagramSocket(port);
    	while(true){
			socket.receive(inPacket);
			byte[] outBuf=new byte[DATA_LENGTH]; //傳送緩衝
			outPacket=new DatagramPacket(outBuf, DATA_LENGTH, inPacket.getAddress(), inPacket.getPort());	
			//接收資料
			String receiveStr=new String(inPacket.getData(), 0, inPacket.getLength());
			System.out.println(receiveStr);
			if(receiveStr.equals("connect")){//處理第一次嘗試連線
InetAddress host=InetAddress.getLocalHost();
String ip=host.getHostAddress();
String hostname=host.getHostName();
String data="success--"+ip+"--"+hostname;
outBuf=data.getBytes();
outPacket.setData(outBuf);
socket.send(outPacket); 
}
			
    	}
    }
   
}

客戶端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;


public class Client {
   private int dest_port;
   private String dest_ip;
   private final int TIMTOUT=5000;//5秒UDP超時
   private final int DATA_LENGTH=1024*4;//������ݳ���
   public Client(String dest_ip,int dest_port) {
	  this.dest_ip=dest_ip;
	  this.dest_port=dest_port;			  
   } 
   public void init(){
	   byte[] inBuf=new byte[DATA_LENGTH]; //���յ����
	   DatagramPacket inPacket=new DatagramPacket(inBuf, DATA_LENGTH);//�������
	   DatagramPacket outPacket=null;//������
	   try {
		  DatagramSocket socket=new DatagramSocket();
		  socket.setSoTimeout(TIMTOUT);
		  outPacket=new DatagramPacket(inBuf, DATA_LENGTH, InetAddress.getByName(dest_ip), dest_port);//������
		  Scanner scanner=new Scanner(System.in);
		  while(scanner.hasNext()){
			  byte[] buf=scanner.nextLine().getBytes();
			  outPacket.setData(buf);
			  socket.send(outPacket);
			  socket.receive(inPacket);
			  System.out.println(new String(inPacket.getData(), 0, DATA_LENGTH));
		  }
	   } catch (Exception e) {
			e.printStackTrace();
	   }
	   
   }
}