簡體   English   中英

我怎么知道應用程序是連接到 wifi 還是以太網使用 java?

[英]How can I know the application is link to wifi or ethernet use java?

我想在 mac 和 windows 上檢測網絡是 wifi 還是以太網。

NetworkInterface.getNetworkInterfaces()

此代碼可以獲得網絡接口的名稱,但我不知道網絡是wifi還是ethernet。請幫助我....

(如果我理解您的問題)您可以嘗試類似查看不同Network InterfacesLocal Address 如果wlan有一個私有IP Address ,您可以假設它使用無線技術連接到網絡。 如果一個eth有一個私有IP Address ,你可以假設它是通過以太網連接到網絡的。 我不知道這是否是 100% 有效。 這不是我的領域。

import java.net.*;
import java.util.*;

public class Main {

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

            Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
            InetSocketAddress inetAddr= new InetSocketAddress(nifAddresses.nextElement(),0);

            System.out.println("Interface: " + nif.getName());
            DatagramSocket socket = new DatagramSocket(inetAddr);
            System.out.println(socket.getLocalAddress());
            System.out.println("");
        } catch (SocketException ex) {
            System.out.println(ex.toString());
        }
        catch(NoSuchElementException ex)
        {
            //System.out.println(ex.toString());
        }
     }
}  

輸出

Interface: lo
/127.0.0.1

Interface: eth4 //Number changed!
/131.555.555.55

查看此輸出,我假設eth4具有網絡連接。

在應用程序代碼中,您無法知道,也不應該知道。 在 Java 應用程序運行的級別上,網絡之間沒有區別,您所擁有的只是一個 TCP/IP 堆棧,您無法根據它確定您正在使用的網絡類型。

您必須用本機代碼編寫一些與低級操作系統功能接口的東西(不要問我是什么或如何,這顯然取決於操作系統)來獲取該信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM