| 网站首页 | 文章中心 | 电子书下载 | 矢量图库 | 视频教程 | 素材下载 | 程序代码下载 | JS代码 | 论坛 | 
常用软件类:
|杀毒安全 |联络聊天 |网络软件 |多媒体类 |系统工具 |图形图像 |系统工具 |应用软件 |行业软件
开发设计类:
|动画制作 |图像处理 |3D设计 |操作系统 |站长学院 |网络相关 |WEB设计 |数据库类 |程序开发
JAVA编程读取MAC地址技巧

作者:佚名    文章来源:网络    点击数:    更新时间:2007-7-12
 

 

  4 程序编写

  我们先来分析ipconfig/all的输出格式:

  图1
点击放大此图片

  从图1中我们看到MAC地址包含的行为:“ Physical Address. . . . . . . . . : 00-10-DC-A9-0B-2C”。为了找到MAC地址,我们一行一行读取字符,只要找到字符串“ Physical Address. . . . . . . . . :”,就可以找到MAC地址了。下面是实现的程序片段:

以下是引用片段:

  Process process = Runtime.getRuntime().exec("cmd /c ipconfig /all");
  BufferedReader bufferedReader =
  new BufferedReader(new InputStreamReader (process.getInputStream()));
  while ( (line=bufferedReader.readLine()) != null){
  if(line.indexOf("Physical Address. . . . . . . . . :") != -1){
  if(line.indexOf(":") != -1){
  physicalAddress = line.substring(line.indexOf(":")+2);
  :

在上面的程序中,为了读取命令输出的字符,利用子进程process生成了一个数据流缓冲区。

  依据上面的代码,我们编写了一个类ReadMAC,见下面程序的源代码:

以下是引用片段:
import java.io.*;
  public class ReadMAC {
  public static String physicalAddress = "read MAC error!";
  public ReadMAC() {
  }
  public static String checkPhysicalAddress(){
  try{
  String line;
  Process process = Runtime.getRuntime().exec("cmd /c ipconfig /all");
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
  while ( (line=bufferedReader.readLine()) != null){
  if(line.indexOf("Physical Address. . . . . . . . . :") != -1){
  if(line.indexOf(":") != -1){
  physicalAddress = line.substring(line.indexOf(":")+2);
  break; //找到MAC,推出循环
  }
  }
  }
  process.waitFor();
  }catch(Exception e){
  e.printStackTrace();
  }
  return physicalAddress;
  }
  public static void main(String[] args) {
  System.out.println("本机的MAC地址是: "+ ReadMAC.checkPhysicalAddress());
  }
  }

  编译运行该程序的输出结果如图2所示。

  图2

  由于每一台计算机的MAC地址都不同,所以该程序在不同计算机上运行结果都会不一样。

  5 结束语

  作为一个跨平台语言,编写的JAVA程序一般都与硬件无关,因而能运行在不同的操作系统环境。但这给编写底层相关的程序时带来不便。

  Java的应用程序都存在着一个与其运行环境相联系的Runtime对象,利用该对象可执行外部命令,在WindowsXP/NT/2000环境中的命令IPCONFIG的输出包含有MAC地址。本文编写的Java程序,执行外部命令IPCONFIG,并通过分析该命令的输入流而获得本机的MAC地址。由于IPCONFIG命令是操作系统命令,所以该方法既方便又可靠。

  以上讨论的程序适合于Windows XP/NT/2000操作系统,因为它是基于该操作系统的命令IPCONFIG格式的。由于不同操作系统读取MAC地址的命令、以及命令输出格式的不同,所以该程序不能直接运用到其它系统。要移植到其它系统只需针对命令的输出格式稍作修改。

上一页  [1] [2] 


  • 上一篇文章:

  • 下一篇文章: 没有了
  • 相关文章