java获取本机名称、IP、MAC地址和网卡名称 java获取本机名称、IP、MAC地址和网卡名称

摘自:https://blog.csdn.net/Dai_Haijiao/article/details/80364370 

2018年05月18日 14:53:19
阅读数:134
  1. import java.net.InetAddress;
  2. import java.net.NetworkInterface;
  3. public class IpConfig {
  4. @SuppressWarnings("static-access")
  5. public static void main(String[] args) throws Exception {
  6. InetAddress ia = null;
  7. try {
  8. ia = ia.getLocalHost();
  9. String localname = ia.getHostName();
  10. String localip = ia.getHostAddress();
  11. System.out.println("本机名称是:" + localname);
  12. System.out.println("本机的ip是 :" + localip);
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. }
  16. InetAddress ia1 = InetAddress.getLocalHost();// 获取本地IP对象
  17. System.out.println("本机的MAC是 :" + getMACAddress(ia1));
  18. }
  19. // 获取MAC地址的方法
  20. private static String getMACAddress(InetAddress ia) throws Exception {
  21. // 获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。
  22. byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
  23. // 下面代码是把mac地址拼装成String
  24. StringBuffer sb = new StringBuffer();
  25. for (int i = 0; i < mac.length; i++) {
  26. if (i != 0) {
  27. sb.append("-");
  28. }
  29. // mac[i] & 0xFF 是为了把byte转化为正整数
  30. String s = Integer.toHexString(mac[i] & 0xFF);
  31. // System.out.println("--------------");
  32. // System.err.println(s);
  33. sb.append(s.length() == 1 ? 0 + s : s);
  34. }
  35. // 把字符串所有小写字母改为大写成为正规的mac地址并返回
  36. return sb.toString().toUpperCase();
  37. }
  38. }

输出结果如下:

本机名称是:PC-DaiHaijiao
本机的ip是 :172.16.0.31

本机的MAC是 :00-FF-0D-99-5E-1E


  1. import java.net.Inet4Address;
  2. import java.net.InetAddress;
  3. import java.net.NetworkInterface;
  4. import java.util.Enumeration;
  5. public class NetworkInterfaceTest {
  6. public static void main(String[] args) throws Exception {
  7. // 获得本机的所有网络接口
  8. Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
  9. while (nifs.hasMoreElements()) {
  10. NetworkInterface nif = nifs.nextElement();
  11. // 获得与该网络接口绑定的 IP 地址,一般只有一个
  12. Enumeration<InetAddress> addresses = nif.getInetAddresses();
  13. while (addresses.hasMoreElements()) {
  14. InetAddress addr = addresses.nextElement();
  15. if (addr instanceof Inet4Address) { // 只关心 IPv4 地址
  16. System.out.println("网卡接口名称:" + nif.getName());
  17. System.out.println("网卡接口地址:" + addr.getHostAddress());
  18. System.out.println();
  19. }
  20. }
  21. }
  22. }
  23. }

输出结果如下:

网卡接口名称: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