java通过ip获取客户端Mac地址的小例子
package com.yswc.dao.sign;
import java.io.bufferedreader;
import java.io.inputstreamreader;
import java.util.regex.matcher;
import java.util.regex.pattern;
/**
*
* 获取mac地址
*
* @author
*
* 2011-12
*
*/
public class getmacaddress {
public static string callcmd(string[] cmd) {
string result = "";
string line = "";
try {
process proc = runtime.getruntime().exec(cmd);
inputstreamreader is = new inputstreamreader(proc.getinputstream());
bufferedreader br = new bufferedreader (is);
while ((line = br.readline ()) != null) {
result += line;
}
}catch(exception e) {
e.printstacktrace();
}
return result;
}
/**
*
*
*
* @param cmd
* 第一个命令
*
* @param another
* 第二个命令
*
* @return 第二个命令的执行结果
*
*/
public static string callcmd(string[] cmd,string[] another) {
string result = "";
string line = "";
try {
runtime rt = runtime.getruntime();
process proc = rt.exec(cmd);
proc.waitfor(); // 已经执行完第一个命令,准备执行第二个命令
proc = rt.exec(another);
inputstreamreader is = new inputstreamreader(proc.getinputstream());
bufferedreader br = new bufferedreader (is);
while ((line = br.readline ()) != null) {
result += line;
}
}catch(exception e) {
e.printstacktrace();
}
return result;
}
/**
*
*
*
* @param ip
* 目标ip,一般在局域网内
*
* @param sourcestring
* 命令处理的结果字符串
*
* @param macseparator
* mac分隔符号
*
* @return mac地址,用上面的分隔符号表示
*
*/
public static string filtermacaddress(final string ip, final string sourcestring,final string macseparator) {
string result = "";
string regexp = "((([0-9,a-f,a-f]{1,2}" + macseparator + "){1,5})[0-9,a-f,a-f]{1,2})";
pattern pattern = pattern.compile(regexp);
matcher matcher = pattern.matcher(sourcestring);
while(matcher.find()){
result = matcher.group(1);
if(sourcestring.indexof(ip) <= sourcestring.lastindexof(matcher.group(1))) {
break; // 如果有多个ip,只匹配本ip对应的mac.
}
}
return result;
}
/**
*
*
*
* @param ip
* 目标ip
*
* @return mac address
*
*
*
*/
public static string getmacinwindows(final string ip){
string result = "";
string[] cmd = {"cmd","/c","ping " + ip};
string[] another = {"cmd","/c","arp -a"};
string cmdresult = callcmd(cmd,another);
result = filtermacaddress(ip,cmdresult,"-");
return result;
}
/**
*
* @param ip
* 目标ip
* @return mac address
*
*/
public static string getmacinlinux(final string ip){
string result = "";
string[] cmd = {"/bin/sh","-c","ping " + ip + " -c 2 && arp -a" };
string cmdresult = callcmd(cmd);
result = filtermacaddress(ip,cmdresult,":");
return result;
}
/**
* 获取mac地址
*
* @return 返回mac地址
*/
public static string getmacaddress(string ip){
string macaddress = "";
macaddress = getmacinwindows(ip).trim();
if(macaddress==null||"".equals(macaddress)){
macaddress = getmacinlinux(ip).trim();
}
return macaddress;
}
public static void main(string[] args) {
string mac=getmacaddress("192.168.1.102");
system.out.println("mac:"+mac);
}
}
上一篇: Java递归 遍历目录的小例子
下一篇: C#计算字符串相似性的方法