class="article_content clearfix">
class="htmledit_views">
在JAVA中有时候会需要定位到某台电脑,而通过IP定位显然是不行的,有一种解决方案是通过定位到电脑的物理地址来定位电脑,这是本文要介绍的内容。
1. PhysicalAddressUtil
class="has">class="language-java">package com.jetsum.web.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import test.Test;
public class PhysicalAddress {
public static String getMACAddress() {
String address = "";
String os = System.getProperty("os.name");
if (os != class="tags" href="/tags/NULL.html" title=null>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()) != class="tags" href="/tags/NULL.html" title=null>null) {
if (line.indexOf("Physical Address") != -1) {
int index = line.indexOf(":");
address = line.subclass="tags" href="/tags/STRING.html" title=string>string(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()) != class="tags" href="/tags/NULL.html" title=null>null) {
int index = line.indexOf("硬件地址");
if (index != -1) {
address = line.subclass="tags" href="/tags/STRING.html" title=string>string(index + 4);
break;
}
}
br.close();
return address.trim();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE,
class="tags" href="/tags/NULL.html" title=null>null, ex);
}
}
}
return address;
}
}
2.使用
class="has">class="language-java">String address = PhysicalAddressUtil.getMACAddress() ;