import java.net.InetAddress; import java.net.NetworkInterface; public class IpConfig { @SuppressWarnings("static-access") public static void main(String[] args) throws Exception { InetAddress ia = null; try { ia = ia.getLocalHost(); String localname = ia.getHostName(); String localip = ia.getHostAddress(); System.out.println("本机名称是:" + localname); System.out.println("本机的ip是 :" + localip); } catch (Exception e) { e.printStackTrace(); } InetAddress ia1 = InetAddress.getLocalHost();// 获取本地IP对象 System.out.println("本机的MAC是 :" + getMACAddress(ia1)); } // 获取MAC地址的方法 private static String getMACAddress(InetAddress ia) throws Exception { // 获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。 byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress(); // 下面代码是把mac地址拼装成String StringBuffer sb = new StringBuffer(); for (int i = 0; i < mac.length; i++) { if (i != 0) { sb.append("-"); } // mac[i] & 0xFF 是为了把byte转化为正整数 String s = Integer.toHexString(mac[i] & 0xFF); // System.out.println("--------------"); // System.err.println(s); sb.append(s.length() == 1 ? 0 + s : s); } // 把字符串所有小写字母改为大写成为正规的mac地址并返回 return sb.toString().toUpperCase(); } }
输出结果如下:
本机名称是:PC-DaiHaijiao
本机的ip是 :172.16.0.31
本机的MAC是 :00-FF-0D-99-5E-1E
import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; public class NetworkInterfaceTest { public static void main(String[] args) throws Exception { // 获得本机的所有网络接口 Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces(); while (nifs.hasMoreElements()) { NetworkInterface nif = nifs.nextElement(); // 获得与该网络接口绑定的 IP 地址,一般只有一个 Enumeration<InetAddress> addresses = nif.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if (addr instanceof Inet4Address) { // 只关心 IPv4 地址 System.out.println("网卡接口名称:" + nif.getName()); System.out.println("网卡接口地址:" + addr.getHostAddress()); System.out.println(); } } } } }
输出结果如下:
网卡接口名称:lo
网卡接口地址:127.0.0.1
网卡接口名称:eth0
网卡接口地址:172.16.0.31
网卡接口名称:eth2
网卡接口地址:192.168.220.1
网卡接口名称:wlan2
网卡接口地址:192.168.0.108
网卡接口名称:eth8
网卡接口地址:192.168.138.1