简体   繁体   中英

How can i get list of MAC address and IP address of computer through java?

I m developing a software where i need the list of IP address and MAC address of computer through java code. Is there any way to get the list of ip address and mac address?

Thanks

Since JDK 1.6, Java developers are able to access network card detail via NetworkInterface class.

            InetAddress ip;
    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());

For multiple ip addresses :

                    java.util.Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        en.hasMoreElements(); ) {
        NetworkInterface iface = en.nextElement();
        List<InterfaceAddress> addrs = iface.getInterfaceAddresses();
        //For each network interfaces iterate through each ip address
        for(InterfaceAddress addr : addrs) {
                         ip = addr.getAddress();
                          //Process the IP ...

Sample code to run commands from java program,

    Process p;
    String cmd="ifconfig-a";
    p = Runtime.getRuntime().exec(cmd);
    BufferedReader br = new BufferedReader(
    new InputStreamReader(p.getInputStream()));
    while ((s = br.readLine()) != null)
    System.out.println("line: " + s);
    p.waitFor();
    System.out.println ("exit: " + p.exitValue());
    p.destroy();

Output:

line: eth0      Link encap:Ethernet  HWaddr 00:13:D3:DE:5A:A4  --->MAC address in linux

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM