因为最近有程序需要在java环境下获取网卡id,研究了sun网站的相关资料(感谢令公子的连接)。
测试整理了一下,分享给大家。
思路是通过调用windows环境下的ipconfig命令和linux环境下的ifconfig命令来获取网卡信息:
分为四个程序文件:
test.java;networkinfo.java;windowsnetworkinfo.java;linuxnetworkinfo.java
//————–test.java——–
package netcardinfo;
public class test {
public test() {
}
public networkinfo nti = new windowsnetworkinfo();
public static void main(string[] args) {
test test1 = new test();
try {
system.out.println("network infos");
system.out.println("operating system:" + system.getproperty("os.name"));
system.out.println("ip/localhost:" + test1.nti.getlocalhost());
system.out.println("mac address:" + test1.nti.getmacaddress());
system.out.println("domain:" + test1.nti.getnetworkdomain());
}
catch(throwable t) {
t.printstacktrace();
}
}
}
//———end file———
//———–networkinfo.java———-
package netcardinfo;
import java.net.*;
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public abstract class networkinfo{
private static final string localhost = "localhost";
public static final string nslookup_cmd = "nslookup";
public abstract string parsemacaddress() throws parseexception;
/** not too sure of the ramifications here, but it just doesnt seem right */
public string parsedomain() throws parseexception { return parsedomain(localhost); }
/** universal entry for retrieving mac address */
public final static string getmacaddress() throws ioexception {
try {
networkinfo info = getnetworkinfo();
string mac = info.parsemacaddress();
return mac;
}
catch(parseexception ex)
{ ex.printstacktrace();
throw new ioexception(ex.getmessage());
}
}
/** universal entry for retrieving domain info */
public final static string getnetworkdomain() throws ioexception{
try {
networkinfo info = getnetworkinfo();
string domain = info.parsedomain();
return domain;
}
catch(parseexception ex)
{ex.printstacktrace();
throw new ioexception(ex.getmessage());
}
}
protected string parsedomain(string hostname) throws parseexception{
// get the address of the host we are looking for – verification
java.net.inetaddress addy = null;
try {
addy = java.net.inetaddress.getbyname(hostname);
}
catch ( unknownhostexception e ) {
e.printstacktrace();
throw new parseexception(e.getmessage(),0);
}
// back out to the hostname – just validating
hostname = addy.getcanonicalhostname();
string nslookupcommand = nslookup_cmd + " " + hostname;
// run the lookup command
string nslookupresponse = null;
try {
nslookupresponse = runconsolecommand(nslookupcommand);
}
catch ( ioexception e ){
e.printstacktrace();
throw new parseexception(e.getmessage(), 0);
}
stringtokenizer tokeit = new stringtokenizer(nslookupresponse,"\n",false);
while( tokeit.hasmoretokens() )
{ string line = tokeit.nexttoken();
if( line.startswith("name:")){line = line.substring(line.indexof(":") + 1);
line = line.trim();
if( isdomain(line, hostname)){line = line.substring(hostname.length()+1);
return line;
}
}
}
return "n.a.";
}
private static boolean isdomain(string domaincandidate, string hostname)
{ pattern domainpattern = pattern.compile("[\\w-]+\\.[\\w-]+\\.[\\w-]+\\.[\\w-]+");
matcher m = domainpattern.matcher(domaincandidate);
return m.matches() && domaincandidate.startswith(hostname);
}
protected string runconsolecommand(string command) throws ioexception {
process p = runtime.getruntime().exec(command);
inputstream stdoutstream = new bufferedinputstream(p.getinputstream());
stringbuffer buffer= new stringbuffer();
for (;;) {
int c = stdoutstream.read();
if (c == -1) break;
buffer.append((char)c);
}
string outputtext = buffer.tostring();
stdoutstream.close();
return outputtext;
}
/** sort of like a factory… */
private static networkinfo getnetworkinfo() throws ioexception {
string os = system.getproperty("os.name");
if(os.startswith("windows")) {
return new windowsnetworkinfo();
}
else if(os.startswith("linux")) {
return new linuxnetworkinfo();
}
else {
throw new ioexception("unknown operating system: " + os);
}
}
protected string getlocalhost() throws parseexception {
try {
return java.net.inetaddress.getlocalhost().gethostaddress();
}
catch (java.net.unknownhostexception e ) {
e.printstacktrace();
throw new parseexception(e.getmessage(), 0);
}
}
}
//———-end file————-
//—————windowsnetworkinfo.java————-
package netcardinfo;
import java.io.*;
import java.text.*;
import java.util.regex.*;
public class windowsnetworkinfo extends networkinfo{
public static final string ipconfig_command = "ipconfig /all";
public string parsemacaddress() throws parseexception {
// run command
string ipconfigresponse = null;
try {
ipconfigresponse = runconsolecommand(ipconfig_command);
}
catch ( ioexception e ) {
e.printstacktrace();
throw new parseexception(e.getmessage(), 0);
}
// get localhost address
string localhost = getlocalhost();
java.util.stringtokenizer tokenizer = new java.util.stringtokenizer(ipconfigresponse, "\n");
string lastmacaddress = null;
while(tokenizer.hasmoretokens()){
string line = tokenizer.nexttoken().trim();
// see if line contains ip address, this means stop if weve already seen a mac address
if(line.endswith(localhost) && lastmacaddress != null){
return lastmacaddress;
}
// see if line might contain a mac address
int macaddressposition = line.indexof(":");
if(macaddressposition <= 0) {continue;}
// trim the line and see if it matches the pattern
string macaddresscandidate = line.substring(macaddressposition + 1).trim();
if(ismacaddress(macaddresscandidate)) {
lastmacaddress = macaddresscandidate;
continue;
}
}
parseexception ex = new parseexception("cannot read mac address from [" + ipconfigresponse + "]", 0);
ex.printstacktrace();
throw ex; }
private static boolean ismacaddress(string macaddresscandidate){
pattern macpattern = pattern.compile("[0-9a-fa-f]{2}-[0-9a-fa-f]{2}-[0-9a-fa-f]{2}-[0-9a-fa-f]{2}-[0-9a-fa-f]{2}-[0-9a-fa-f]{2}");
matcher m = macpattern.matcher(macaddresscandidate);
return m.matches();
}
}
//————–end file————–
//————linuxnetworkinfo.java———-
package netcardinfo;
import java.io.*;
import java.text.*;
public class linuxnetworkinfo extends networkinfo{
public static final string ipconfig_command = "ifconfig";
public string parsemacaddress() throws parseexception{
string ipconfigresponse = null;
try {
ipconfigresponse = runconsolecommand(ipconfig_command);
}
catch ( ioexception e ) {
e.printstacktrace();
throw new parseexception(e.getmessage(), 0);
}
string localhost = null;
try {
localhost = java.net.inetaddress.getlocalhost().gethostaddress();
}
catch(java.net.unknownhostexception ex)
{
ex.printstacktrace();
throw new parseexception(ex.getmessage(), 0);
}
java.util.stringtokenizer tokenizer = new java.util.stringtokenizer(ipconfigresponse, "\n");
string lastmacaddress = null;
while(tokenizer.hasmoretokens()) {
string line = tokenizer.nexttoken().trim();
boolean containslocalhost = line.indexof(localhost) >= 0;
// see if line contains ip address
if(containslocalhost && lastmacaddress != null) {
return lastmacaddress;
}
// see if line contains mac address
int macaddressposition = line.indexof("hwaddr");
if(macaddressposition <= 0) {continue;}
string macaddresscandidate = line.substring(macaddressposition + 6).trim();
if(ismacaddress(macaddresscandidate)) {
lastmacaddress = macaddresscandidate;
continue;
}
}
parseexception ex = new parseexception("cannot read mac address for " + localhost + " from [" + ipconfigresponse + "]", 0);
ex.printstacktrace();
throw ex;
}
public string parsedomain(string hostname)
throws parseexception {return "";}
private final boolean ismacaddress(string macaddresscandidate) {
if(macaddresscandidate.length() != 17) return false;
return true;}
}
程序在jdk1.4,windows2000下编译测试通过,linux环境需对test.java略做修改,条件所限未测试。
