java ip 获取了两个_用Java获取本地的多个IP地址

翻API翻出来的,拿出来晒晒。。。

特别适用于获取本地的多个IP地址

import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; public class GetIP {     public static void main(String[] args) throws UnknownHostException,             SocketException {         System.out.println("Host:/t" + InetAddress.getLocalHost() + "/n");         Enumeration en = NetworkInterface                 .getNetworkInterfaces();         Enumeration addresses;         while (en.hasMoreElements()) {             NetworkInterface networkinterface = en.nextElement();             System.out.println(networkinterface.getName());             addresses = networkinterface.getInetAddresses();             while (addresses.hasMoreElements()) {                 System.out.println("/t"                         + addresses.nextElement().getHostAddress() + "");             }         }     } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取 MAC 地址是一个常见的需求,在 Java 中可以通过以下两种方式来获取: 1. 使用 NetworkInterface 类获取 MAC 地址。 ```java import java.net.*; import java.util.*; public class MacAddressUtil { public static String getMacAddress() throws Exception { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); byte[] mac = network.getHardwareAddress(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); } return sb.toString(); } } ``` 2. 使用 Runtime 类执行命令获取 MAC 地址。 ```java import java.io.*; public class MacAddressUtil { public static String getMacAddress() throws Exception { Process process = Runtime.getRuntime().exec("ifconfig"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { if (line.contains("ether")) { String[] words = line.trim().split("\\s+"); return words[1]; } } return null; } } ``` 第一种方法使用 NetworkInterface 类来获取 MAC 地址,这种方式可靠性较高,但是需要注意的是,如果主机有多个网卡,可能会获取到多个 MAC 地址。此外,该方法需要在主机上运行,因此不适用于获取远程主机的 MAC 地址。 第二种方法使用 Runtime 类执行命令来获取 MAC 地址,这种方式比较简单,但是可靠性较差,因为它依赖于命令输出的格式。此外,该方法需要在主机上运行,因此也不适用于获取远程主机的 MAC 地址

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值