新闻中心

EEPW首页>嵌入式系统>设计应用> JAVA得到网卡物理地址(Windows和Linux)

JAVA得到网卡物理地址(Windows和Linux)

作者: 时间:2016-09-12 来源:网络 收藏

在我们在写程序的过程中,有些时候需要知道一些电脑的硬件信息,比如我们写一些需要注册的程序的时候,就需要得到某个电脑特定的信息,一般来说,网卡的物理地址是不会重复的,我们正好可以用它来做为我们识别一台电脑的标志.那如何得到网卡的物理地址呢?我们可以借助于ProcessBuilder这个类,这个类是JDK1.5新加的,以前也可以用Runtime.exce这个类.在此我们将演示一下如何在Windows和Linux环境下得到网卡的物理地址.

本文引用地址://m.amcfsurvey.com/article/201609/305055.htm

/*

* Test.java

*

* Created on 2007-9-27, 9:11:15

*

* To change this template, choose Tools   Templates

* and open the template in the editor.

*/

package test2;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Properties;

import java.util.logging.Level;

import java.util.logging.Logger;

/**

*

* @author hadeslee

*/

public class Test {

public static String getMACAddress() {

String address = ;

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

System.out.println(os);

if (os != null) {

if (os.startsWith(Windows)) {

try {

ProcessBuilder pb = new ProcessBuilder(ipconfig, /all);

Process p = pb.start();

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

String line;

while ((line = br.readLine()) != null) {

if (line.indexOf(Physical Address) != -1) {

int index = line.indexOf(:);

address = line.substring(index + 1);

break;

}

}

br.close();

return address.trim();

} catch (IOException e) {

}

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

try {

ProcessBuilder pb = new ProcessBuilder(ifconfig);

Process p = pb.start();

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

String line;

while((line=br.readLine())!=null){

int index=line.indexOf(硬件地址);

if(index!=-1){

address=line.substring(index+4);

break;

}

}

br.close();

return address.trim();

} catch (IOException ex) {

Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);

}

}

}

return address;

}

public static void main(String[] args) {

System.out.println( + Test.getMACAddress());

}

}

我们可以看一下1.5新增的ProcessBuilder这个类,这个类比起以前用Runtime.exec来说,要强大一些,它可以指定一个环境 变量,并指定程序运行时的目录空间,并且也可以得到程序运行时的环境变量.因为ipconfig这个命令已经是system32里面的,所以不需要我们另外再设环境变量或者指定程序的运行时目录空间.我们直接用就可以了,然后得到进程的输出流,就可以分析出我们所需要的东西了.是不是挺简单的呢

此程序可以得到windows下和Linux下的网卡地址,不过LINUX要是中文版的,英文版的也一样,只不过把字替换一下就可以了。这样我们的程序就有了两个平台的实现。



关键词:

评论


相关推荐

技术专区

关闭