java 获取本地mac_java获取本地mac总结(摘录整理)

这篇博客介绍了如何在Java中获取本地MAC地址,分别提供了针对Windows和Linux操作系统的实现方式,包括通过执行系统命令获取和使用Java的NetworkInterface类进行纯Java方式的获取。并提供了详细的代码示例。
摘要由CSDN通过智能技术生成

import java.net.InetAddress;

import java.io.InputStream;

import java.io.BufferedInputStream;

import java.io.IOException;

import java.text.ParseException;

import java.util.StringTokenizer;

public final class NetworkInfo {

private final static String getMacAddress() throws IOException {

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

try {

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

return windowsParseMacAddress(windowsRunIpConfigCommand());

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

return linuxParseMacAddress(linuxRunIfConfigCommand());

} else {

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

}

} catch (ParseException ex) {

ex.printStackTrace();

throw new IOException(ex.getMessage());

}

}

/*

* Linux stuff

*/

private final static String linuxParseMacAddress(String ipConfigResponse) throws ParseException {

String localHost = null;

try {

localHost = InetAddress.getLocalHost().getHostAddress();

} catch (java.net.UnknownHostException ex) {

ex.printStackTrace();

throw new ParseException(ex.getMessage(), 0);

}

StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");

String lastMacAddress = null;

while (tokenizer.hasMoreTokens()) {

String line = tokenizer.nextToken().trim();

boolean containsLocalHost = line.indexOf(localHost) >= 0;

// see if line contains IP address

if (containsLocalHost && lastMacAddress != null) {

return lastMacAddress;

}

// see if line contains MAC address

int macAddressPosition = line.indexOf("HWaddr");

if (macAddressPosition <= 0)

continue;

String macAddressCandidate = line.substring(macAddressPosition + 6).trim();

if (linuxIsMacAddress(macAddressCandidate)) {

lastMacAddress = macAddressCandidate;

continue;

}

}

ParseException ex = new ParseException("cannot read MAC address for " + localHost

+ " from [" + ipConfigResponse + "]", 0);

ex.printStackTrace();

throw ex;

}

private final static boolean linuxIsMacAddress(String macAddressCandidate) {

if (macAddressCandidate.length() != 17){

return false;

}

return true;

}

private final static String linuxRunIfConfigCommand() throws IOException {

Process p = Runtime.getRuntime().exec("ifconfig");

InputStream stdoutStream = new BufferedInputStream(p.getInputStream());

StringBuffer buffer = new StringBuffer();

for (;;) {

int c = stdoutStream.read();

if (c == -1)

break;

buffer.append((char) c);

}

String outputText = buffer.toString();

stdoutStream.close();

return outputText;

}

/*

* Windows stuff

*/

private final static String windowsParseMacAddress(String ipConfigResponse)

throws ParseException {

String localHost = null;

try {

localHost = InetAddress.getLocalHost().getHostAddress();

} catch (java.net.UnknownHostException ex) {

ex.printStackTrace();

throw new ParseException(ex.getMessage(), 0);

}

StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");

String lastMacAddress = null;

while (tokenizer.hasMoreTokens()) {

String line = tokenizer.nextToken().trim();

// see if line contains IP address

if (line.endsWith(localHost) && lastMacAddress != null) {

return lastMacAddress;

}

// see if line contains MAC address

int macAddressPosition = line.indexOf(":");

if (macAddressPosition <= 0)

continue;

String macAddressCandidate = line.substring(macAddressPosition + 1).trim();

if (windowsIsMacAddress(macAddressCandidate)) {

lastMacAddress = macAddressCandidate;

continue;

}

}

ParseException ex = new ParseException("cannot read MAC address from ["

+ ipConfigResponse + "]", 0);

ex.printStackTrace();

throw ex;

}

private final static boolean windowsIsMacAddress(String macAddressCandidate) {

if (macAddressCandidate.length() != 17){

return false;

}

return true;

}

private final static String windowsRunIpConfigCommand() throws IOException {

Process p = Runtime.getRuntime().exec("ipconfig /all ");

InputStream stdoutStream = new BufferedInputStream(p.getInputStream());

StringBuffer buffer = new StringBuffer();

for (;;) {

int c = stdoutStream.read();

if (c == -1)

break;

buffer.append((char) c);

}

String outputText = buffer.toString();

stdoutStream.close();

return outputText;

}

/*

* Main

*/

public final static void main(String[] args) {

try {

System.out.println("Network infos");

System.out.println("Operating System:" + System.getProperty("os.name"));

System.out.println("IP/Localhost:" + InetAddress.getLocalHost().getHostAddress());

System.out.println("MAC Address:" + getMacAddress());

} catch (Throwable t) {

t.printStackTrace();

}

}

}

方法二:

在Unix/Linux 下通常只有root 用户才有执行ifconfig 命令的权限, 第一种方法中用调用ifconfig 命令的方法获取硬件地址可靠性不好, 普通用户无法正确获取硬件地址,该方法通过纯java的方式很好地解决了此问题

import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.Enumeration;

public class MyMac {

public static void main(String[] args) {

try {

//枚举所有网络接口设备

Enumeration interfaces = NetworkInterface.getNetworkInterfaces();

//循环处理每一个网络接口设备

while (interfaces.hasMoreElements()) {

NetworkInterface face = (NetworkInterface) interfaces.nextElement();

//环回设备(lo)设备不处理

if (!face.getName().equals("lo")) {

//显示当前网络接口设备显示名称

System.out.println("网卡显示名称:" + face.getDisplayName());

//显示当前设备内部名称

System.out.println(" 网卡设备名称:" + face.getName());

// 获取硬件地址

byte[] mac = face.getHardwareAddress();

System.out.println(" 硬件地址(MAC):" + bytes2mac(mac));

}

}

} catch (SocketException se) {

System.err.println("错误:" + se.getMessage());

}

}

private static String bytes2mac(byte[] bytes) {

//MAC 地址应为6 字节

if (bytes.length != 6) {

System.err.println("MAC 地址数据有错! ");

return null;

}

StringBuffer macString = new StringBuffer();

byte currentByte;

for (int i = 0; i < bytes.length; i++) {

//与11110000 作按位与运算以便读取当前字节高4 位

currentByte = (byte) ((bytes[i] & 240) >> 4);

macString.append(Integer.toHexString(currentByte));

//与00001111 作按位与运算以便读取当前字节低4 位

currentByte = (byte) ((bytes[i] & 15));

macString.append(Integer.toHexString(currentByte));

//追加字节分隔符“-”

macString.append("-");

}

//删除多加的一个“-”

macString.delete(macString.length() - 1, macString.length());

//统一转换成大写形式后返回

return macString.toString().toUpperCase();

}

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2011-08-09 14:17

浏览 1371

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值