您的位置:首页 > 运维架构 > Linux

Linux环境下用java查找局域网内所有设备的ip及Mac地址

2018-04-26 14:03 567 查看

工作需要用到在局域网内查找所有在线设备的ip及Mac地址,客户工控机用的是Linux系统,与Windows相比有很多命令不一样,网上查了很多资料,后来找到用Nmap工具进行扫描,对扫描结果进行解析。

本方法需要现在Linux系统上安装Nmap工具。

我这边使用的分别是Centos6.8,和Centos7,亲测有效。

具体代码如下:

import java.io.*; 

import java.net.InetAddress;
import java.util.*; 


import org.apache.commons.lang.StringUtils;


import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;


public class IpUtil{ 

/**
* 获取局域网内所有设备IP与Mac地址
* GDB
* @return
* @throws Exception 
*/
public static List<Map<String, Object>> getIps() throws Exception {
List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
        try {  
            String localIP=InetAddress.getLocalHost().getHostAddress();  
            String os = System.getProperty("os.name");//获取服务器类型
            if (os.startsWith("Linux")) {
            //Linux下获取本机ip,从而截取所属ip区段
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    String name = intf.getName();
                    if (!name.contains("docker") && !name.contains("lo")) {
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress()) {
                                String ipaddress = inetAddress.getHostAddress().toString();
                                if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                localIP = ipaddress;
                                    System.out.println(ipaddress);
                                }
                            }
                        }
                    }
                }
            } 
            System.out.println("localIP  >>>>>>>>>>>>>>>>>>>>>>>>>>>"+localIP);
            String[] net=localIP.split("\\.");  
            int j=Integer.parseInt(net[2]);  
            int a=Integer.parseInt(net[0]);  
            int b=Integer.parseInt(net[1]);
            String command = "";
            if (os.startsWith("Linux")) {
            //Linux下使用nmap工具对本网段端口进行扫描
                command = "nmap -sP "+a+"."+b+"."+j+".0/24";
                System.out.println("command>>>>>>>>>>>>>>>>>>>>>>"+command);
                //command>>>>>>>>>>>>>>>>>>>>>>nmap -sP 192.168.2.0/24
            }
  
            Process p=Runtime.getRuntime().exec(command);  
            LineNumberReader br = new LineNumberReader(new InputStreamReader(  
                    p.getInputStream()));  
            StringBuffer sb = new StringBuffer();  
            String line;  
            while ((line = br.readLine()) != null) {  
                System.out.println(line);  
                sb.append(line).append("*");  
            }  
          System.out.println("*********************");
            System.out.println(sb.toString()); 
            /*Starting Nmap 5.51 ( http://nmap.org ) at 2018-04-25 09:16 EDT
        Nmap scan report for 192.168.2.1
        Host is up (0.00014s latency).
        MAC Address: 20:DC:E6:8B:D1:C8 (Unknown)
        Nmap scan report for 192.168.2.100
        Host is up (0.00085s latency).
        MAC Address: 64:00:6A:21:16:EB (Unknown)
        Nmap scan report for 192.168.2.104
        Host is up (0.0012s latency).
        MAC Address: 70:B3:D5:A9:7F:EE (Unknown)
        Nmap scan report for 192.168.2.105
        Host is up.
        Nmap scan report for 192.168.2.106
        Host is up (0.069s latency).
        MAC Address: DC:F0:90:84:A5:0E (Unknown)
        Nmap done: 256 IP addresses (5 hosts up) scanned in 9.84 seconds*/
            String str = sb.toString();
            str =  str.substring(str.indexOf("EDT*")+4, str.indexOf("*Nmap done:"));
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            System.out.println(str);
            String [] lists = str.split("\\*");
            int l = 0;
            Map<String, Object> map = new HashMap<String, Object>();
            //对返回结果进行解析
            for(int i=0;i<lists.length;i++){
            l++;
            String s = lists[i];
            System.out.println(lists[i]);
            if(StringUtils.startsWith(s, "Nmap scan report for") && (l==1 || l==3)){
            if(l==3){l=1;}
            map = new HashMap<String, Object>();
            map.put("IP", s.substring(21));
            }else if(StringUtils.startsWith(s, "Host is up")){
            continue;
            }else if(StringUtils.startsWith(s, "MAC Address:")&& l==3){
            map.put("Mac", s.substring(13,30));
            result.add(map);
            l=0;
            }else {
            l=0;
    }
            }
            System.out.println(result.toString());
            //result = [{mac=20:DC:E6:8B:D1:C8, ip=192.168.2.1}, {mac=64:00:6A:21:16:EB, ip=192.168.2.100}, {mac=70:B3:D5:A9:7F:EE, ip=192.168.2.104}, {mac=DC:F0:90:84:A5:0E, ip=192.168.2.106}]
            p.destroy();  
            return result;
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
return null;
}
    
} 阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: