程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java完成獲得用戶的MAC地址

java完成獲得用戶的MAC地址

編輯:關於JAVA

java完成獲得用戶的MAC地址。本站提示廣大學習愛好者:(java完成獲得用戶的MAC地址)文章只能為提供參考,不一定能成為您想要的結果。以下是java完成獲得用戶的MAC地址正文


辦法一:將本機地址與局域網內其他機械辨別開來

/**
   * 依據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"));
   }
  
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved