欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现获取用户的MAC地址

程序员文章站 2024-03-06 14:20:44
方法一:将本机地址与局域网内其他机器区分开来 /** * 根据ip地址获取mac地址 * @param ipaddress 127.0.0.1...

方法一:将本机地址与局域网内其他机器区分开来

/**
   * 根据ip地址获取mac地址
   * @param ipaddress 127.0.0.1
   * @return
   * @throws socketexception
   * @throws unknownhostexception
   */
  public static string getlocalmac(string ipaddress) throws socketexception,
      unknownhostexception {
    // todo auto-generated method stub
    string str = "";
    string macaddress = "";
    final string loopback_address = "127.0.0.1";
    // 如果为127.0.0.1,则获取本地mac地址。
    if (loopback_address.equals(ipaddress)) {
      inetaddress inetaddress = inetaddress.getlocalhost();
      // 貌似此方法需要jdk1.6。
      byte[] mac = networkinterface.getbyinetaddress(inetaddress)
          .gethardwareaddress();
      // 下面代码是把mac地址拼装成string
      stringbuilder sb = new stringbuilder();
      for (int i = 0; i < mac.length; i++) {
        if (i != 0) {
          sb.append("-");
        }
        // mac[i] & 0xff 是为了把byte转化为正整数
        string s = integer.tohexstring(mac[i] & 0xff);
        sb.append(s.length() == 1 ? 0 + s : s);
      }
      // 把字符串所有小写字母改为大写成为正规的mac地址并返回
      macaddress = sb.tostring().trim().touppercase();
      return macaddress;
    } else {
      // 获取非本地ip的mac地址
      try {
        system.out.println(ipaddress);
        process p = runtime.getruntime()
            .exec("nbtstat -a " + ipaddress);
        system.out.println("===process=="+p);
        inputstreamreader ir = new inputstreamreader(p.getinputstream());
         
        bufferedreader br = new bufferedreader(ir);
       
        while ((str = br.readline()) != null) {
          if(str.indexof("mac")>1){
            macaddress = str.substring(str.indexof("mac")+9, str.length());
            macaddress = macaddress.trim();
            system.out.println("macaddress:" + macaddress);
            break;
          }
        }
        p.destroy();
        br.close();
        ir.close();
      } catch (ioexception ex) {
      }
      return macaddress;
    }
  }

我们再来看下方法二:

package com.alpha.test;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.linenumberreader;

public class getmac {

	/**
	 * java获取客户端网卡的mac地址
	 * 
	 * @param args
	 */
	public static void main(string[] args) {
		getmac get = new getmac();
		system.out.println("1="+get.getmac());
		system.out.println("2="+get.getmac("127.0.0.1"));
	}

	// 1.获取客户端ip地址( 这个必须从客户端传到后台):
	// jsp页面下,很简单,request.getremoteaddr() ;
	// 因为系统的view层是用jsf来实现的,因此页面上没法直接获得类似request,在bean里做了个强制转换

	// public string getmyip() {
	// try {
	// facescontext fc = facescontext.getcurrentinstance();
	// httpservletrequest request = (httpservletrequest) fc
	// .getexternalcontext().getrequest();
	// return request.getremoteaddr();
	// } catch (exception e) {
	// e.printstacktrace();
	// }
	// return "";
	// }

	// 2.获取客户端mac地址
	// 调用window的命令,在后台bean里实现 通过ip来获取mac地址。方法如下:

	// 运行速度【快】
	public string getmac() {
		string mac = null;
		try {
			process pro = runtime.getruntime().exec("cmd.exe /c ipconfig/all");

			inputstream is = pro.getinputstream();
			bufferedreader br = new bufferedreader(new inputstreamreader(is));
			string message = br.readline();

			int index = -1;
			while (message != null) {
				if ((index = message.indexof("physical address")) > 0) {
					mac = message.substring(index + 36).trim();
					break;
				}
				message = br.readline();
			}
			system.out.println(mac);
			br.close();
			pro.destroy();
		} catch (ioexception e) {
			system.out.println("can't get mac address!");
			return null;
		}
		return mac;
	}

	// 运行速度【慢】
	public string getmac(string ip) {
		string str = null;
		string macaddress = null;
		try {
			process p = runtime.getruntime().exec("nbtstat -a " + ip);
			inputstreamreader ir = new inputstreamreader(p.getinputstream());
			linenumberreader input = new linenumberreader(ir);
			for (; true;) {
				str = input.readline();
				if (str != null) {
					if (str.indexof("mac address") > 1) {
						macaddress = str
								.substring(str.indexof("mac address") + 14);
						break;
					}
				}
			}
		} catch (ioexception e) {
			e.printstacktrace(system.out);
			return null;
		}
		return macaddress;
	}
}

方法三,更精简一些

import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.linenumberreader;

public class macaddress {
 string ip;
 string mac;
 public macaddress (string ip){
  this.ip = ip;
 }
 public macaddress (){
  this.ip = "0.0.0.0";
 }
 public string getmac(){
  try {
  process p = runtime.getruntime().exec("arp -n");
   inputstreamreader ir = new inputstreamreader(p.getinputstream());
   linenumberreader input = new linenumberreader(ir);
   p.waitfor();
   boolean flag = true;
   string ipstr = "(" + this.ip + ")";
   while(flag) {
    string str = input.readline();
    if (str != null) {
     if (str.indexof(ipstr) > 1) {
      int temp = str.indexof("at");
      this.mac = str.substring(
      temp + 3, temp + 20);
      break;
     }
    } else
    flag = false;
   }
  } catch (ioexception | interruptedexception e) {
   e.printstacktrace(system.out);
  }
  return this.mac;
 }
 public void setip(string ip){
  this.ip = ip;
 }

}

最后要放大招了,小伙伴们看仔细哦

首先要说的是:本方法可以支持外网机器的mac地址获取。 

以前弄了一个只能访问局域网。 有防火墙就访问不了, 但是这个不用担心了。
测试了百度的ip,已经可以获得mac地址

java通过ip获取mac地址-封ip封mac地址

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) {      
     system.out.println(getmacaddress("220.181.111.148"));
   }
  
}