经常在项目中遇到获取本地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地址。