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

时间:2015-06-16 18:02:19

标签: java network-interface

我需要知道如何检测以太网电缆是否插有java插头,我使用NetworkInterface检查接口,但是当拔下电缆并重新插上电源时我需要发出警报。

谢谢大家,我的代码是:

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

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

2 个答案:

答案 0 :(得分:2)

我相信您正走在找到解决方案的正确道路上。使用函数 isUp(),您可以验证此接口是否处于活动状态,这意味着,如果连接了电缆,此功能将返回 true ,如果不是。虽然你错过了一些观点。 以下是您必须采取的步骤:

  1. 获取操作系统中可用的接口列表。

    Enumeration<NetworkInterface> tempNetInterface = null;
    try {
        tempNetInterface = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    ArrayList<NetworkInterface> interfaces = new ArrayList<>(Collections.list(tempNetInterface));
    
  2. 制作另一个仅包含真实接口的列表。请记住,根据机器和操作系统,条件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()是否返回类似&#34; eth0&#34;或&#34; eth1&#34;,如果是,则它是以太网连接。

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

    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);
    }
    
  5. 希望它有所帮助!

答案 1 :(得分:0)

这是旧线程,但可能对研究人员有用。 根据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();
    }

}