首页 | 互联网 | IT动态 | IT培训 | Cisco | Windows | Linux | Java | .Net | Oracle | 软件测试 | C/C++ | 嵌入式开发 | 存储世界 | 服务器
网络设备 | IDC | 安全 | 求职招聘 | 数字网校 | 网页设计 | 平面设计 | 技术专题 | 电子书下载 | 教学视频 | 源码下载 | 搜索 | 博客 | 论坛
中国IT实验室Linux频道
Google
首页 入门 Linux编程 系统管理 网络管理 Linux认证 Unix/BSD Linux数据库 Linux集群 Linux手册 Linux下载 Ubuntu 论坛 专题 RSS
您现在的位置: 中国IT实验室 >> Linux >> 系统管理 >> 系统管理 >> 正文

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

  在我们在写程序的过程中,有些时候需要知道一些电脑的硬件信息,比如我们写一些需要注册的程序的时候,就需要得到某个电脑特定的信息,一般来说,网卡的物理地址是不会重复的,我们正好可以用它来做为我们识别一台电脑的标志。那如何得到网卡的物理地址呢?我们可以借助于ProcessBuilder这个类,这个类是JDK1.5新加的,以前也可以用Runtime.exce这个类。在此我们将演示一下如何在Windows和Linux环境下得到网卡的物理地址。
 
  
/*
* 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要是中文版的,英文版的也一样,只不过把字替换一下就可以了。这样我们的程序就有了两个平台的实现。
 

【责编:Zenghui】
中国IT教育
相关产品和培训
文章评论
 友情推荐链接
 专题推荐

 ·防范Linux病毒 打造没有病毒的乐土…
 ·Linux Shell编程实用指南…
 ·Linux日志分析与管理
 ·揭密Linux内存管理
 ·邮件服务Sendmail应用配置
 ·Linux 安全管理…
 ·Linux 下DNS服务器架设攻略…
 ·Linux 下的路由的配置与应用…
 ·专题:Apache实用手册
 ·全面剖析Linux文件系统
 今日更新
 认证培训
 频道精选
 Windows频道导航