如何检测以太网电缆是否已连接到 Windows 上的 Java

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

我需要知道如何使用 Java 检测以太网电缆是否插入或拔出,​​我使用 NetworkInterface 检查接口,但我需要在电缆插入时发出警报拔掉再插上。

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

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

我相信您在寻找解决方案的道路上是正确的。使用函数 isUp() 您可以验证此接口是否处于活动状态,这意味着,如果有电缆连接,此函数将 return true ,如果不是 false。尽管您缺少一些要点。 以下是您必须采取的步骤:

  1. 获取OS中可用的接口列表。

    Enumeration<NetworkInterface> tempNetInterface = null;
    try {
        tempNetInterface = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    ArrayList<NetworkInterface> interfaces = new ArrayList<>(Collections.list(tempNetInterface));
    
  2. 制作另一个仅包含真实接口的列表。请记住,根据机器和 OS 条件 if (iNet.getHardwareAddress() != null) 可能不足以确定此接口是否真实,方法 isVirtual() 不会给你真相,但有这个问题还有许多其他解决方案。

    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. 从实际界面中您应该可以识别出哪些是以太网连接。 (如果它们是无线的,则不会涉及电缆)。对于 windows,您可以验证方法 getName() return 是否类似于 "eth0" 或 "eth1",如果是,则它是以太网连接。

    if (iNet.getName().contains("eth")) {
        System.out.println("It is ETHERNET");
    }
    
  4. 找到要监视的 NetworkInterface 对象后,只需创建线程例程来验证 isUp() 状态被改变了。您可以通过多种方式执行此操作,如果您使用的是 Swing,则可能需要创建一个 SwingWorker 来更新您的 UI,或者创建一个 ActionListener,或者一个 Observer 或者甚至一个简单的 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);
    }
    

希望对大家有所帮助!

这是旧线程,但可能对研究人员有用。 根据JR的回复修改

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();
    }

}