Find the MAC address of all devices connected to t

2019-05-11 00:15发布

问题:

I'm trying to build a software that checks what devices are connected to my home network and return a list of those device's MAC address every 10 minutes or so.

My approach was to ping all of the possible IP addresses on the network and call "arp -a" afterwards.

The following code works to find if a device is registered on an IP address, but I don't know how to get the MAC address from this.

try {
            String currentIP = InetAddress.getLocalHost().toString();
            String subnet = getSubnet(currentIP);
            System.out.println("subnet: " + subnet);

            for (int i=1;i<254;i++){

                String host = subnet + i;
                System.out.println("Checking :" + host);

                if (InetAddress.getByName(host).isReachable(timeout)){
                    System.out.println(host + " is reachable");
                    try {
                        Socket connected = new Socket(subnet, port);
                    }
                    catch (Exception s) {
                        System.out.println(s);
                    }
                }
            }
        }
        catch(Exception e){
            System.out.println(e);
        }

Any suggestions?

回答1:

Try this one.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class App{

   public static void main(String[] args){

    InetAddress ip;
    try {

        ip = InetAddress.getLocalHost();
        System.out.println("Current IP address : " + ip.getHostAddress());

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        byte[] mac = network.getHardwareAddress();

        System.out.print("Current MAC address : ");

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
        }
        System.out.println(sb.toString());

    } catch (UnknownHostException e) {

        e.printStackTrace();

    } catch (SocketException e){

        e.printStackTrace();

    }

   }

}

This NetworkInterfaceNetworkInterface.getHardwareAddress() method is only allowed to access localhost MAC address, not remote host MAC address.

Note : You can't do this in remotely for PC or Device in java.But you can do it by using C# and WMI - WMI with netowrk in .NET language



回答2:

You're blindly assuming IPV4, which is not so reasonable anymore these days.

And you're trying to dig out information that routers and access points have no good reason for disclosing in the first place (at least not to robots who won't authenticate themselves as an admin with access rights to the router's or access point's admin page).