日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

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

發布時間:2023/11/27 生活经验 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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) |

總結

以上是生活随笔為你收集整理的java 获取linux mac_java在linux获得ip地址和mac的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。