获取MAC地址,java版本

星期二, 2010-12-14 | Author: Lee | JAVA-and-J2EE | 4,953 views

获取MAC地址,java版本,从jdk1.6支持,不啰嗦了,上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.liyz.mac;
 
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
 
public class TestMac {
 
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		List<String> list = getMacSinceJDK6();
		for (String s : list) {
			System.out.println(s);
		}
	}
 
	private static String hexByte(byte b) {
		String s = Integer.toHexString(b);
		int len = s.length();
		for (int i = len; i < 8; i++) {
			s = "0" + s;
		}
		return s.substring(6).toUpperCase();
	}
 
	/**
	 * 获取MAC地址,length为0时,为获取失败,有可能有多个mac地址
	 * 
	 * @since jdk6
	 * @return List<String>
	 */
	private static List<String> getMacSinceJDK6() {
		List<String> list = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> el = NetworkInterface
					.getNetworkInterfaces();
			while (el.hasMoreElements()) {
				byte[] mac = el.nextElement().getHardwareAddress();
				if (mac == null || mac.length == 0) {
					continue;
				}
				StringBuffer sb = new StringBuffer();
				for (byte b : mac) {
					sb.append(hexByte(b));
					sb.append("-");
				}
				sb.deleteCharAt(sb.length() - 1);
				list.add(sb.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}

Tags: , ,

文章作者: Lee

本文地址: https://www.pomelolee.com/713.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta