java 获取linux mac_java在linux获得ip地址和mac

以前在linux下获取ip和mac一般使用jni,调用linux的ioctl。当然也有使用shell获取的。

发现在jdk 6下已经实现了,java.net.NetworkInterface上面有静态方法可以获取到所有本地网卡信息。注意的是用Java的InetAddress.getLocalHost()方法在Linux下只能得到127.0.0.1,只能在Windows下获取正确的ip地址.

代码如下

package test;

import java.io.*;

import java.net.*;

import java.util.*;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import static java.lang.System.out;

public class ListNIFs

{

public static void main(String args[]) throws SocketException {

Enumerationnets = NetworkInterface.getNetworkInterfaces();

for (NetworkInterface netIf : Collections.list(nets)) {

String name =  netIf.getDisplayName();

if(name.equals("eth0"))

{

out.printf("Display name: %s\n", netIf.getDisplayName());

out.printf("Name: %s\n", netIf.getName());

byte [] mac = netIf.getHardwareAddress();

String macs =Hex.encodeHexStr(mac);

out.printf("Name: %s\n", macs);

//displaySubInterfaces(netIf);

out.printf("\n");

}

}

printHardwareAddresses();

}

static void printHardwareAddresses() throws SocketException {

if (System.getProperty("os.name").equals("Linux")) {

// Read all available device names

Listdevices = new ArrayList<>();

Pattern pattern = Pattern.compile("^ *(.*):");

try (FileReader reader = new FileReader("/proc/net/dev")) {

BufferedReader in = new BufferedReader(reader);

String line = null;

while( (line = in.readLine()) != null) {

Matcher m = pattern.matcher(line);

if (m.find()) {

devices.add(m.group(1));

}

}

} catch (IOException e) {

e.printStackTrace();

}

// read the hardware address for each device

for (String device : devices) {

try (FileReader reader = new FileReader("/sys/class/net/" + device + "/address")) {

BufferedReader in = new BufferedReader(reader);

String addr = in.readLine();

System.out.println(String.format("%5s: %s", device, addr));

} catch (IOException e) {

e.printStackTrace();

}

}

} else {

// use standard API for Windows & Others (need to test on each platform, though!!)

}

}

阅读(3566) | 评论(0) | 转发(0) |

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值