如何用java获取网卡地址(MAC Address)
来源:互联网 发布:电脑显示未识别的网络 编辑:程序博客网 时间:2024/05/01 23:54
我们经常要取得一些和机器硬件相关的信息来进行一些特殊授权的操作,如文件加密等,这时,针对网卡地址的处理是一种不错的选择,因为硬件厂商已经将网卡的编号固化到了网卡上,而这个编号是全球唯一的,绝对不会重复。
如何取得MAC Address,SUN没有提供官方的直接实现,这就要我们自己动脑了。你可以借助jni和C等第三方手段来间接获取,这里提供另外一种方法,也能满足需求,代码如下:
package com.pure.util;
import java.io.*;
import java.util.*;
import java.util.regex.*;
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 final static List<String> getMacAddressList() throws IOException {
final ArrayList<String> macAddressList = new ArrayList<String>();
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() {
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<String> addressList=getMacAddressList();
StringBuffer sb=new StringBuffer();
for (Iterator<String> iter = addressList.iterator(); iter.hasNext();) {
sb.append(iter.next());
}
return sb.toString();
} catch (IOException e) {
return null;
}
}
public final static void main(String[] args) {
try {
System.out.println(" MAC Address: " + getMacAddress());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
可以看到,这里使用平台自带shell来取得网卡地址,然后用java对文本进行筛选,取得需要的网卡地址。
- 如何用java获取网卡地址(MAC Address)
- 如何用ASP来获取网卡的MAC地址
- 如何用VC++开发读取网卡MAC地址的程序
- 如何用VC++开发读取网卡MAC地址的程序
- 如何用VC++开发读取网卡MAC地址的程序
- 如何用php得到网卡的MAC地址
- 如何用C语言获取网卡的mac地址?(当然,你也可以用类似方法获取所有ip)
- 如何用 MAC Address 找到 IP
- 纯Java代码获取网卡MAC地址
- java获取网卡的mac地址
- java获取网卡的mac地址
- java通过ip获取网卡MAC地址
- 获取网卡MAC地址
- 获取网卡MAC地址
- 获取网卡Mac地址
- 获取网卡MAC地址
- 获取网卡MAC地址
- 获取网卡MAC地址
- .NET2005将出来了,请问现在如果让你们选,你们会选J2EE还是.NET.
- Mono
- WebSphere快速入门(1)
- WebSphere快速入门(2)
- WebSphere快速入门(3)
- 如何用java获取网卡地址(MAC Address)
- [HOOPS]二维点向三维空间投影
- WebSphere快速入门(4)
- WebSphere快速入门(5)
- WebSphere快速入门(6)
- WebSphere快速入门(7)
- WebSphere快速入门(8)
- 他们又说……
- WebSphere快速入门(9)