java如何获取Linux操作系统下的ip地址和网

2024-11-22 10:04:01
推荐回答(1个)
回答1:

以下代码需要 JDK 6 及以后版本,如果是 JDK 6 以下版本的话,没有直接获得 MAC 的 API。

import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.util.Enumeration; public class NetworkInfo { private final static char[] HEX = "0123456789ABCDEF".toCharArray(); public static void main(String[] args) throws SocketException { for(Enumeration i = NetworkInterface.getNetworkInterfaces(); i.hasMoreElements(); ) { NetworkInterface ni = i.nextElement(); System.out.println("NETWORK CARD NAME: " + ni.getDisplayName()); System.out.println("MAC: " + toMacString(ni.getHardwareAddress())); for(Enumeration j = ni.getInetAddresses(); j.hasMoreElements(); ) { System.out.println(" " + j.nextElement()); } } } private static String toMacString(byte[] bys) { if(bys == null) { return null; } char[] chs = new char[bys.length * 3 - 1]; for(int i = 0, k = 0; i < bys.length; i++) { if(i > 0) { chs[k++] = '-'; } chs[k++] = HEX[(bys[i] >> 4) & 0xf]; chs[k++] = HEX[bys[i] & 0xf]; } return new String(chs); }}