得到局域网下设备机的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();
	   }
	   
   }
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值