Java获取局域网中所有ip和Mac地址

Java获取局域网中所有ip和Mac地址

  1. 定义一个Util

public class IpAndMacUtil {
    /**
     * 获取本机Mac地址
     * @param ia
     * @return
     * @throws SocketException
     */
    private static volatile int num = 0;


    public static String getLocalMac(InetAddress ia) throws SocketException {
        //获取网卡,获取地址
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        String MAC="";
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                MAC += "-";
            }
            //字节转换为整数
            int temp = mac[i] & 0xff;
            String str = Integer.toHexString(temp);
            if (str.length() == 1) {
                MAC = MAC+"0"+str;
            } else {
                MAC += str;
            }
        }
        return MAC;
    }


    /**
     * 获得局域网所有的ip
     * @return
     * @throws IOException
     */
    public static List<String> getAllIp() throws IOException {
        InetAddress host=InetAddress.getLocalHost();
        String hostAddress=host.getHostAddress();
        int pos=hostAddress.lastIndexOf(".");

        //获得本机ip的网段
        String bigNet=hostAddress.substring(0,pos+1);
        List<String> ips= Collections.synchronizedList(new ArrayList<>());
        for (int i=0;i<=225;i++){
            String ip=bigNet+i;
            new Thread(()->{
                try {
                    Process process = Runtime.getRuntime().exec("ping "+ip+" -w 280 -n 1");
                    InputStream inputStream=process.getInputStream();
                    InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"GBK");
                    BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
                    String line=null;
                    String isActive=null;
                    while((line=bufferedReader.readLine()) != null) {
                        if(!line.equals("")){
                            isActive=bufferedReader.readLine().substring(0,2);
                            break;
                        }
                    }
                    if(isActive.equals("来自")){
                        ips.add(ip);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                num++;
            }).start();
        }
        while (num!=225) {}
        return ips;
    }



    /**
     * 根据ip,获取mac地址
     * @param ip
     * @return
     * @throws Exception
     */
    public static String getMacAddress(String ip) throws Exception{
        String result = command("ping "+ip+" -n 2");
        if(result.contains("TTL")){
            result = command("arp -a "+ip);
        }
        String regExp = "([0-9A-Fa-f]{2})([-:][0-9A-Fa-f]{2}){5}";
        Pattern pattern = Pattern.compile(regExp);
        Matcher matcher = pattern.matcher(result);
        StringBuilder mac = new StringBuilder();
        while (matcher.find()) {
            String temp = matcher.group();
            mac.append(temp);
        }
        return mac.toString();
    }

    private static String command(String cmd) throws Exception{
        Process process = Runtime.getRuntime().exec(cmd);
        process.waitFor();
        InputStream in = process.getInputStream();
        StringBuilder result = new StringBuilder();
        byte[] data = new byte[256];
        while(in.read(data) != -1){
            String encoding = System.getProperty("sun.jnu.encoding");
            result.append(new String(data,encoding));
        }
        return result.toString();
    }
}
  1. service调用util

public List<PadMACReq> queryMAC(){
        List<PadMACReq> padMACReq = new ArrayList<>();
        try {
            //获取本机ip,MAC地址
            InetAddress ia = InetAddress.getLocalHost();
            String ip=ia.toString().split("/")[1];
            PadMACReq localMAC = new PadMACReq(ip, IpAndMacUtil.getLocalMac(ia));
            padMACReq.add(localMAC);

            //获取局域网ip,MAC地址
            List<String> allIp = IpAndMacUtil.getAllIp();
            for(int i = 0 ; i < allIp.size() ; i++){
                String macAddress = IpAndMacUtil.getMacAddress(allIp.get(i));
                if(macAddress.isEmpty()){
                    continue;
                }
                PadMACReq macAndIp = new PadMACReq(allIp.get(i),macAddress);
                padMACReq.add(macAndIp);
                System.out.println("正在获取ip,MAC地址");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return padMACReq;
    }
  1. 返回类

public class PadMACReq {
    /** 终端名称ip*/
    private String name;
    /** mac地址*/
    private String mac;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1daynes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值