java怎样获取以太网的MAC地址
2015-12-26 · 做真实的自己 用良心做教育
读取ipconfig/all里面的内容:
public static String checkPhysicalAddress() {
String physicalAddress ="";
try {
String line;
Process process = Runtime.getRuntime().exec("cmd /c ipconfig /all");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int temp=1;
int switchon=0;
while ((line = bufferedReader.readLine()) != null) {
if(switchon ==1){
temp++;
}
if(line.indexOf("以太网适配器 本地连接:") !=-1){
switchon=1;
continue;
}
if (temp == 5) {
line = bufferedReader.readLine();
System.out.println("1:"+line);
if (line.indexOf(":") != -1) {
physicalAddress = line.substring(line.indexOf(":") + 2).replaceAll("-", "").trim();
break; //找到MAC,推出循环
}
}
}
//process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
return physicalAddress;
}
一行一行的读取命令行的东西,直到我们想要的一行
如下图我们需要的是“以太网适配器 本地链接:”这里面的物理地址,上面的代码就是找到这一行,然后再下去五行就是我们要的MAC地址
2023-07-25 广告
#include<sys/ioctl.h>
#include<netinet/if_ether.h>
#include<net/if.h>
#include<linux/sockios.h>
#include<stdio.h>
#include<string.h>
char *device="eth0"; //eth0是网卡设备名
unsigned char macaddr[ETH_ALEN]; //ETH_ALEN(6)是MAC地址的长度
main()
{
int s=socket(AF_INET,SOCK_DGRAM,0); //建立套接口
int i;
struct ifreq req;
strcpy(req.ifr_name,device); //将设备名作为输入参数传入
int err = ioctl(s,SIOCGIFHWADDR,&req); //执行取MAC地址操作
close(s);
if(err!=-1)
{
memcpy(macaddr,req.ifr_hwaddr.sa_data,ETH_ALEN); //取输出的MAC地址
for(i=0;i<ETH_ALEN;i++)
printf("%3d:",macaddr[i]);
}
}
/*然后用gcc编译,再用./a.out