Java获取本地IP和mac地址

2023-12-14 12:36:16

经常在项目中遇到获取本地IP和mac的需求,下面给一个以java编写的例子,代码如下:

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

public class NetworkInfo {
    public static void main(String[] args) {
        try {
            InetAddress ipAddress = InetAddress.getLocalHost();
            System.out.println("IP Address: " + ipAddress.getHostAddress());

            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(ipAddress);
            byte[] macAddressBytes = networkInterface.getHardwareAddress();
            StringBuilder macAddress = new StringBuilder();
            for (int i = 0; i < macAddressBytes.length; i++) {
                macAddress.append(String.format("%02X%s", macAddressBytes[i], (i < macAddressBytes.length - 1) ? "-" : ""));
            }
            System.out.println("MAC Address: " + macAddress.toString());
        } catch (UnknownHostException | SocketException e) {
            e.printStackTrace();
        }
    }
}

这段代码将打印出请求端的IP地址和MAC地址。

请注意,获取MAC地址可能需要具有适当的权限,并且在某些情况下可能无法获取到准确的MAC地址。

文章来源:https://blog.csdn.net/dhp811/article/details/134907325
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。