java获取mac为空_Java 获取MAC

该Java代码实现了根据操作系统类型(Windows或Linux)执行不同命令获取MAC地址,并使用正则表达式匹配MAC地址,最终返回第一个找到的MAC地址。如果未找到地址,则返回空字符串。
摘要由CSDN通过智能技术生成

package com.utils;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class MacAddress

{

private static final String[] windowsCommand = {"ipconfig", "/all"};

private static final String[] linuxCommand = {"/sbin/ifconfig", "-a"};

private static final Pattern macPattern = Pattern.compile(".*((:?[0-9a-f]{2}[-:]){5}[0-9a-f]{2}).*", Pattern.CASE_INSENSITIVE);

private static List getMacAddressList() throws IOException {

ArrayList macAddressList = new ArrayList();

final String os = System.getProperty("os.name");

final String[] command;

if (os.startsWith("Windows")) {

command = windowsCommand;

} else if (os.startsWith("Linux")) {

command = linuxCommand;

} else {

throw new IOException("Unknown operating system: " + os);

}

final Process process = Runtime.getRuntime().exec(command);

// Discard the stderr

new Thread() {

@Override

public void run() {

try {

InputStream errorStream = process.getErrorStream();

while (errorStream.read() != -1) {

}

errorStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}.start();

// Extract the MAC addresses from stdout

BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

for (String line = null; (line = reader.readLine()) != null;) {

Matcher matcher = macPattern.matcher(line);

if (matcher.matches()) {

//macAddressList.add(matcher.group(1));

macAddressList.add(matcher.group(1).replaceAll("[-:]", ""));

}

}

reader.close();

return macAddressList;

}

public static String getMacAddress() {

try {

List addressList = getMacAddressList();

if (addressList.isEmpty()) {

return "";

}

return addressList.get(0);

} catch (IOException e) {

e.printStackTrace();

return "";

}

}

public static List getMacAddressList2() {

List addressList=new ArrayList();

try {

List temp = getMacAddressList();

addressList=temp;

} catch (IOException e) {

e.printStackTrace();

}

return addressList;

}

public static String[] getMacAddresses() {

try {

return getMacAddressList().toArray(new String[0]);

} catch (IOException e) {

e.printStackTrace();

return new String[0];

}

}

public static void main(String[] args) {

MacAddress mac = new MacAddress();

System.out.println("本电脑的MAC地址为:"+mac.getMacAddress());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值