qiyadeng

专注于Java示例及教程
posts - 84, comments - 152, trackbacks - 0, articles - 34

获取本地主机的MAC地址

Posted on 2005-10-01 23:24 qiyadeng 阅读(857) 评论(0)  编辑  收藏 所属分类: J2EE
前些天,有篇文章,准确的说是代码放到csdn的博客上,本是学习的一个笔记,但是既然关心的人很多,于是再一次把它转贴过了,那个博客已经不再用了。

 1/*
 2 FileName:MACHomework.java
 3 Author:流浪小子
 4 Date:2004-7-5
 5 E-mail:qiyadeng@hotmail.com
 6 Purpose:获取本地主机的MAC地址
 7 */

 8import java.io.*;
 9import java.util.*;
10
11public class Main {
12    static private final int MACLength = 18;
13
14    public static void main(String args[]) {
15        System.out.print("本机的物理地址是:");
16        System.out.println(getMACAddress());
17    }

18
19    static public String getMACAddress() {
20        SysCommand syscmd = new SysCommand();
21        //系统命令
22        String cmd = "cmd.exe /c ipconfig/all";
23        Vector result;
24        result = syscmd.execute(cmd);
25        return getCmdStr(result.toString());
26    }

27
28    static public String getCmdStr(String outstr) {
29        String find = "Physical Address. . . . . . . . . :";
30        int findIndex = outstr.indexOf(find);
31        if (findIndex == -1{
32            return "未知错误!";
33        }
 else {
34            return outstr.substring(findIndex + find.length() + 1, findIndex
35                    + find.length() + MACLength);
36        }

37    }

38}

39
40//SysCommand类
41class SysCommand {
42    Process p;
43
44    public Vector execute(String cmd) {
45        try {
46            Start(cmd);
47            Vector vResult = new Vector();
48            DataInputStream in = new DataInputStream(p.getInputStream());
49            BufferedReader myReader = new BufferedReader(new InputStreamReader(
50                    in));
51            String line;
52            do {
53                line = myReader.readLine();
54                if (line == null{
55                    break;
56                }
 else {
57                    vResult.addElement(line);
58                }

59            }
 while (true);
60            myReader.close();
61            return vResult;
62        }
 catch (Exception e) {
63            return null;
64
65        }

66
67    }

68
69    public void Start(String cmd) {
70        try {
71            if (p != null{
72                kill();
73            }

74            Runtime sys = Runtime.getRuntime();
75            p = sys.exec(cmd);
76
77        }
 catch (Exception e) {
78
79        }

80    }

81
82    public void kill() {
83        if (p != null{
84            p.destroy();
85            p = null;
86        }

87    }

88
89}

90

只有注册用户登录后才能发表评论。


网站导航: