如何使用java获取我们自己的无线LAN IP地址

时间:2017-03-17 19:53:19

标签: java

以下代码提供以太网地址 但我需要获得Wirless LAN地址

InetAddress inet;
    try {
        inet = InetAddress.getLocalHost();
        myIp.setText(inet.getHostAddress());
    } catch (UnknownHostException ex) {
        Logger.getLogger(frontPageController.class.getName()).log(Level.SEVERE, null, ex);
    }

但获取无线局域网IP地址的代码是什么?

2 个答案:

答案 0 :(得分:1)

这是一个如何使用java.net.NetworkInterface探索网络接口的示例:

@Test
    public void test() throws Exception {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            // drop inactive
            if (!networkInterface.isUp())
                continue;

            // smth we can explore
            Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
            while(addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                System.out.println(String.format("NetInterface: name [%s], ip [%s]",
                        networkInterface.getDisplayName(), addr.getHostAddress()));
            }
        }
    }

答案 1 :(得分:0)

下面的代码用于根据类型识别以太网或wifi的IP-

//useIPv4=true if you want to get ipv4 address
//type="eth0" if you want to get ethernet interface (eth0) IP : change with correct interface name
//type="wlan0" if you want to use wifi interface (wlan0)  : change with correct interface name
public static String getIPAddress(boolean useIPv4, String type) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress();
                        boolean isIPv4 = sAddr.indexOf(':')<0;
                        if(intf.getDisplayName().equalsIgnoreCase(type)) { //checking here the interface type of your choice
                            if (useIPv4) {
                                if (isIPv4)
                                    return sAddr;
                            } else {
                                if (!isIPv4) {
                                    int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
                                    return delim < 0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "ERROR";
    }