5 种使用 Java 获取 WIFI IP 地址和 MAC 地址的方法及代码示例

本文将介绍 5 种使用 Java 获取 WIFI IP 地址和 MAC 地址的方法,并提供完整的代码示例。

1. 使用 Java 的 InetAddress 类

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class WifiInfo {
    public static void main(String[] args) {
        try {
            InetAddress ip = InetAddress.getLocalHost();
            System.out.println('WIFI IP 地址:' + ip.getHostAddress());
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            byte[] mac = network.getHardwareAddress();
            System.out.print('WIFI MAC 地址:');
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format('%02X%s', mac[i], (i < mac.length - 1) ? '-' : ''));
            }
            System.out.println(sb.toString());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}

2. 使用 Java 的 java.net.NetworkInterface 类

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class WifiInfo {
    public static void main(String[] args) {
        Enumeration<NetworkInterface> nets;
        try {
            nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets)) {
                if (netint.isUp() && !netint.isLoopback()) {
                    Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
                    for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                        if (inetAddress.getHostAddress().contains('.')) {
                            System.out.println('WIFI IP 地址:' + inetAddress.getHostAddress());
                        }
                    }
                    byte[] mac = netint.getHardwareAddress();
                    System.out.print('WIFI MAC 地址:');
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        sb.append(String.format('%02X%s', mac[i], (i < mac.length - 1) ? '-' : ''));
                    }
                    System.out.println(sb.toString());
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}

3. 使用 Java 的 jnetpcap 库

jnetpcap 是一个开源的 Java 网络抓包库,可以用来获取网络接口的信息。

下载地址:http://jnetpcap.com/

import org.jnetpcap.Pcap;
import org.jnetpcap.PcapIf;

import java.util.ArrayList;
import java.util.List;

public class WifiInfo {
    public static void main(String[] args) {
        List<PcapIf> alldevs = new ArrayList<PcapIf>(); // Will be filled with NICs
        StringBuilder errbuf = new StringBuilder(); // For any error msgs

        /* Retrieve the device list */
        int r = Pcap.findAllDevs(alldevs, errbuf);
        if (r != Pcap.OK) {
            System.err.printf('Can't read list of devices, error is %s', errbuf
                    .toString());
            return;
        }

        /* Print out the device list */
        for (PcapIf device : alldevs) {
            byte[] mac = device.getHardwareAddress();
            if (mac == null) {
                continue; // Skip devices without a MAC address
            }
            System.out.println('WIFI MAC 地址:' + asString(mac));
            List<PcapAddr> addrs = device.getAddresses();
            for (PcapAddr addr : addrs) {
                if (addr.getAddr().getFamily() == WinPcapSockAddr.AF_INET) {
                    String ip = addr.getAddr().toString();
                    System.out.println('WIFI IP 地址:' + ip.substring(1));
                }
            }
        }
    }

    private static String asString(byte[] mac) {
        StringBuilder buf = new StringBuilder();
        for (byte b : mac) {
            if (buf.length() != 0) {
                buf.append(':');
            }
            if (b >= 0 && b < 16) {
                buf.append('0');
            }
            buf.append(Integer.toHexString((b < 0) ? b + 256 : b).toUpperCase());
        }
        return buf.toString();
    }
}

4. 使用 Java 的 Apache Commons Net 库

Apache Commons Net 是一个开源的 Java 网络库,提供了一些网络相关的类和方法,包括获取网络接口信息。

下载地址:https://commons.apache.org/proper/commons-net/

import org.apache.commons.net.util.SubnetUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class WifiInfo {
    public static void main(String[] args) {
        Enumeration<NetworkInterface> interfaces;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                if (networkInterface.isUp() && !networkInterface.isLoopback()) {
                    System.out.println('WIFI MAC 地址:' + asString(networkInterface.getHardwareAddress()));
                    Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
                        if (!address.isLinkLocalAddress() && !address.isLoopbackAddress()) {
                            SubnetUtils subnet = new SubnetUtils(address.getHostAddress() + '/24');
                            String[] addressesInSubnet = subnet.getInfo().getAllAddresses();
                            for (String addr : addressesInSubnet) {
                                if (!addr.equals(address.getHostAddress())) {
                                    System.out.println('WIFI IP 地址:' + addr);
                                }
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    private static String asString(byte[] mac) {
        StringBuilder buf = new StringBuilder();
        for (byte b : mac) {
            if (buf.length() != 0) {
                buf.append(':');
            }
            if (b >= 0 && b < 16) {
                buf.append('0');
            }
            buf.append(Integer.toHexString((b < 0) ? b + 256 : b).toUpperCase());
        }
        return buf.toString();
    }
}

5. 使用 Java 的 jmdns 库

jmdns 是一个纯 Java 的 mDNS 实现,可以用来发现局域网内的设备。

下载地址:https://github.com/jmdns/jmdns

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
import java.io.IOException;
import java.net.InetAddress;

public class WifiInfo {
    public static void main(String[] args) throws IOException {
        JmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());
        jmdns.addServiceListener('_http._tcp.local.', new ServiceListener() {
            public void serviceAdded(ServiceEvent event) {
                System.out.println('Service added: ' + event.getInfo());
            }

            public void serviceRemoved(ServiceEvent event) {
                System.out.println('Service removed: ' + event.getInfo());
            }

            public void serviceResolved(ServiceEvent event) {
                ServiceInfo info = event.getInfo();
                System.out.println('WIFI IP 地址:' + info.getInet4Addresses()[0].getHostAddress());
                System.out.println('WIFI MAC 地址:' + info.getPropertyString('mac'));
            }
        });
        System.in.read();
        jmdns.close();
    }
}

注意:需要在局域网内有支持 mDNS 协议的设备才能获取到 IP 地址和 MAC 地址。

总结

本文介绍了 5 种使用 Java 获取 WIFI IP 地址和 MAC 地址的方法,并提供了完整的代码示例。希望本文能帮助您解决在 Java 开发中获取 WIFI 信息的难题。

Java 获取 WIFI IP 地址和 MAC 地址的 5 种方法及代码示例

原文地址: https://www.cveoy.top/t/topic/mPla 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录