我怎么知道应用程序链接到wifi或以太网使用java?

问题描述 投票:0回答:2

我希望在mac和windows上检测网络是wifi或以太网。

NetworkInterface.getNetworkInterfaces()

这段代码可以得到网络接口的名称,但我不知道网络是wifi还是以太网。请帮帮我....

java desktop-application ethernet
2个回答
0
投票

在应用程序代码中,您无法知道,您不应该知道。在Java应用程序运行的级别上,网络之间没有区别,您拥有的只是TCP / IP堆栈,并且无法根据您正在处理的网络类型来确定。

您必须在本机代码中编写一些与低级操作系统功能接口的东西(并且不要问我什么或如何,显然它依赖于操作系统)来获取该信息。


0
投票

(如果我理解你的问题)你可能会尝试类似于查看不同Local AddressNetwork Interfaces。如果wlan有私人IP Address,你可以假设它使用无线技术连接到网络。如果eth有私人IP Address,你可以假设它通过以太网连接到网络。我不知道这是否100%有效。这不是我的领域。

import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ListNets {

    public static void main(String args[]) throws SocketException {

        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) {
        try {
            NetworkInterface nif = netint;
            if(nif==null){
                System.err.println("Error getting the Network Interface");
                return;
            }
            //System.out.println("Preparing to using the interface: "+nif.getName());
            Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
            InetSocketAddress inetAddr= new InetSocketAddress(nifAddresses.nextElement(),0);

            //socket.bind(new InetSocketAddress(nifAddresses.nextElement(), 0));
            System.out.println("Preparing to using the interface: "+nif.getName());
            DatagramSocket socket = new DatagramSocket(inetAddr);
            System.out.println(socket.getLocalAddress());
            System.out.println("Interface setted");
        } catch (SocketException ex) {
            System.out.println(ex.toString());
        }
        catch(NoSuchElementException ex)
        {
            //System.out.println(ex.toString());
        }
     }
}  
© www.soinside.com 2019 - 2024. All rights reserved.