How can I detect the ethernet cable is connected with Java on Windows

3.8k views Asked by At

I need to know how to detect if the ethernet cable is plugged or unplugged using Java, I use NetworkInterface to check the interfaces, but I need to do an alert when the cable is unplugged and plugged again.

ArrayList<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

    for (NetworkInterface info : interfaces){
        if(info.isUp()){
            System.out.println(info.getName());
        }
    }
2

There are 2 answers

0
selami tastan On BEST ANSWER

This is old thread, but may be useful for researchers. Modified according to response of J R.

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

public class EthernetCableDetector implements Runnable{

    private NetworkInterface iNet;
    private boolean isRunning = true;
    private BooleanProperty pluged = new SimpleBooleanProperty(false);

    public boolean isPluged() {
        return pluged.get();
    }

    public BooleanProperty plugedProperty() {
        return pluged;
    }

    public void setPluged(boolean pluged) {
        this.pluged.set(pluged);
    }

    public EthernetCableDetector(String localAddress) {
        /**
         * Acquire the list of interfaces available in your OS.
         */
        Enumeration<NetworkInterface> tempNetInterface = null;
        try {
            tempNetInterface = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        ArrayList<NetworkInterface> interfaces = new ArrayList<>(Collections.list(tempNetInterface));

        /**
         *Make another list containing only the real interfaces.
         * Remember that depending on the machine and OS the condition if (iNet.getHardwareAddress() != null)
         * may not be enought to find out if this interface is real or not, the method isVirtual() won't give
         * you the truth but there are many other solutions for this problem.
         */
        ArrayList<NetworkInterface> realInterfaces = new ArrayList<>(Collections.list(tempNetInterface));
        for (NetworkInterface iNet : interfaces) {
            try {
                if (iNet.getHardwareAddress() != null) { //This verification might not be enought to find if a Interface is real.
                    realInterfaces.add(iNet);
                }
                /** From the real interface you should identify which ones are ethernet connections.
                 *  (if they are wireless there will be no cables involved). For windows you can verify
                 *  if the method getName() returns something like "eth0" or "eth1", if yes it is a ethernet connection.
                 */
                if (iNet.getName().contains("eth") && iNet.getInetAddresses().hasMoreElements() && iNet.getInetAddresses().nextElement().getHostAddress().equals(localAddress)) {
                    System.out.println(localAddress + " Found.");
                    this.iNet = iNet;
                    /*
                    boolean previousStatus = iNet.isUp();
                    if (iNet.isUp() != previousStatus) {
                        // Interface cable must habe been plugged or unplugged.
                        previousStatus = iNet.isUp();
                        System.out.println("Cable status has changed " + iNet.isUp());
                    }
                    */
                }
            } catch (SocketException ex) {
                //TODO handle exception
            }
        }

    }

    @Override
    public void run() {
        Globals.pause(5000);
        boolean previousStatus = false;
        try {
            previousStatus = iNet.isUp();
            setPluged(previousStatus);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        System.out.println("Cable status = " + previousStatus);
        while(isRunning)
        {
            Globals.pause(250);
            try {
                setPluged(iNet.isUp());
                if (iNet.isUp() != previousStatus) {
                    // Interface cable must habe been plugged or unplugged.
                    previousStatus = iNet.isUp();
                    System.out.println("Cable status =" + iNet.isUp());
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
    }

    public void stop(){
        isRunning = false;
    }

    public static void main(String[] args) {
        new EthernetCableDetector("192.168.10.26").run();
    }

}
0
brickonthewall On

I believe you are in the right path to find your solution. With the function isUp() you can verify if this interface is active or not, it means, if there is a cable connected this function will return true, if not false. Although you are missing some points. Here are the steps you would have to take:

  1. Acquire the list of interfaces available in your OS.

    Enumeration<NetworkInterface> tempNetInterface = null;
    try {
        tempNetInterface = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    ArrayList<NetworkInterface> interfaces = new ArrayList<>(Collections.list(tempNetInterface));
    
  2. Make another list containing only the real interfaces. Remember that depending on the machine and OS the condition if (iNet.getHardwareAddress() != null) may not be enought to find out if this interface is real or not, the method isVirtual() won't give you the truth but there are many other solutions for this problem.

    for (NetworkInterface iNet : interfaces) {
        try {
            if (iNet.getHardwareAddress() != null) { //This verification might not be enought to find if a Interface is real.
                realInterfaces.add(iNet);
            }
        } catch (SocketException ex) {
            //TODO handle exception
        }
    }
    
  3. From the real interface you should identify which ones are ethernet connections. (if they are wireless there will be no cables involved). For windows you can verify if the method getName() returns something like "eth0" or "eth1", if yes it is a ethernet connection.

    if (iNet.getName().contains("eth")) {
        System.out.println("It is ETHERNET");
    }
    
  4. After you found the NetworkInterface object you want monitor, you just need to create your thread routine that verify if the isUp() status is changed. You can do this in many ways, if you are using Swing you may want to create a SwingWorker to update your UI, or a ActionListener, or a Observer or even a simple Thread.

    if (myNetwokInterface.isUp() != previousStatus) {
        // Interface cable must habe been plugged or unplugged.
        previousStatus = myNetwokInterface.isUp();
        JOptionPane.showMessageDialog(null, "Cable status has changed", "WARNING", JOptionPane.WARNING_MESSAGE);
    }
    

Hope it helps someone!