java 獲取用戶的MAC地址多種方法實(shí)例詳解
java實(shí)現(xiàn)獲取用戶的MAC地址方法:
方法一:將本機(jī)地址與局域網(wǎng)內(nèi)其他機(jī)器區(qū)分開(kāi)來(lái)
/** * 根據(jù)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轉(zhuǎn)化為正整數(shù) String s = Integer.toHexString(mac[i] & 0xFF); sb.append(s.length() == 1 ? 0 + s : s); } // 把字符串所有小寫(xiě)字母改為大寫(xiě)成為正規(guī)的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; } }
我們?cè)賮?lái)看下方法二:
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獲取客戶端網(wǎng)卡的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地址( 這個(gè)必須從客戶端傳到后臺(tái)): // jsp頁(yè)面下,很簡(jiǎn)單,request.getRemoteAddr() ; // 因?yàn)橄到y(tǒng)的VIew層是用JSF來(lái)實(shí)現(xiàn)的,因此頁(yè)面上沒(méi)法直接獲得類似request,在bean里做了個(gè)強(qiáng)制轉(zhuǎn)換 // 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地址 // 調(diào)用window的命令,在后臺(tái)Bean里實(shí)現(xiàn) 通過(guò)ip來(lái)獲取mac地址。方法如下: // 運(yùn)行速度【快】 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; } // 運(yùn)行速度【慢】 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; } }
方法三,更精簡(jiǎn)一些:
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; } }
最后要放大招了,小伙伴們看仔細(xì)哦
首先要說(shuō)的是:本方法可以支持外網(wǎng)機(jī)器的mac地址獲取。
以前弄了一個(gè)只能訪問(wèn)局域網(wǎng)。 有防火墻就訪問(wèn)不了, 但是這個(gè)不用擔(dān)心了。
測(cè)試了百度的ip,已經(jīng)可以獲得mac地址
java通過(guò)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 第一個(gè)命令 * @param another 第二個(gè)命令 * @return 第二個(gè)命令的執(zhí)行結(jié)果 */ public static String callCmd(String[] cmd,String[] another) { String result = ""; String line = ""; try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd); proc.waitFor(); //已經(jīng)執(zhí)行完第一個(gè)命令,準(zhǔn)備執(zhí)行第二個(gè)命令 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 目標(biāo)ip,一般在局域網(wǎng)內(nèi) * @param sourceString 命令處理的結(jié)果字符串 * @param macSeparator mac分隔符號(hào) * @return mac地址,用上面的分隔符號(hào)表示 */ 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; //如果有多個(gè)IP,只匹配本IP對(duì)應(yīng)的Mac. } } return result; } /** * * @param ip 目標(biāo)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 目標(biāo)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; } //做個(gè)測(cè)試 public static void main(String[] args) { System.out.println(getMacAddress("220.181.111.148")); } }
希望本篇文章可以給您幫助
相關(guān)文章
Java枚舉的七種常見(jiàn)用法總結(jié)(必看)
下面小編就為大家?guī)?lái)一篇Java枚舉的七種常見(jiàn)用法總結(jié)(必看)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-11-11基于Java實(shí)現(xiàn)QQ郵箱發(fā)送工具類
我們?cè)谌粘i_(kāi)發(fā)中,需要實(shí)現(xiàn)一個(gè)對(duì)郵箱的發(fā)送,今天就實(shí)現(xiàn)郵箱的發(fā)送工具類,只需要一些注冊(cè)郵箱之后的配置即可,感興趣的小伙伴可以了解下2023-12-12一文秒懂IDEA中每天都在用的Project Structure知識(shí)
這篇文章主要介紹了一文秒懂IDEA中每天都在用的Project Structure知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10java并發(fā)編程專題(十一)----(JUC原子類)數(shù)組類型詳解
這篇文章主要介紹了JAVA JUC原子類 數(shù)組類型詳解的相關(guān)資料,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07spring security自定義認(rèn)證登錄的全過(guò)程記錄
這篇文章主要給大家介紹了關(guān)于spring security自定義認(rèn)證登錄的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12Java switch()括號(hào)內(nèi)參數(shù)的類型要求詳解
這篇文章主要介紹了Java switch()括號(hào)內(nèi)參數(shù)的類型要求,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10全面掌握J(rèn)ava中的循環(huán)控制語(yǔ)句與條件判斷語(yǔ)句的使用
這篇文章主要介紹了Java中的循環(huán)控制語(yǔ)句與條件判斷語(yǔ)句的使用,循環(huán)和判斷是Java編程中流程控制的基礎(chǔ),需要的朋友可以參考下2016-02-02