Méthode 1 : distinguer l'adresse de la machine locale des autres machines du réseau local
/** * Obtenez l'adresse MAC en fonction de l'adresse IP * @param ipAddress 127.0.0.1 * @return * @throws SocketException * @throws UnknownHostException */ public static String getLocalMac(String ipAddress) throws SocketException, UnknownHostException { // TODO Auto -stub de méthode généré String str = ""; String macAddress = "" final String; LOOPBACK_ADDRESS = "127.0.0.1"; // S'il s'agit de 127.0.0.1, obtenez l'adresse MAC locale. if (LOOPBACK_ADDRESS.equals(ipAddress)) { InetAddress inetAddress = InetAddress.getLocalHost(); // Il semble que cette méthode nécessite JDK1.6. byte[] mac = NetworkInterface.getByInetAddress(inetAddress) .getHardwareAddress(); // Le code suivant assemble l'adresse mac dans String StringBuilder sb = new StringBuilder(); { if (i != 0) { sb.append("-"); // mac[i] & 0xFF Il s'agit de convertir l'octet en un entier positif String s = Integer.toHexString(mac[i] & 0xFF); sb.append(s.length() == 1 ? 0 + s : s } // Convertir toutes les chaînes); Remplacez les lettres minuscules par des majuscules pour devenir l'adresse MAC normale et retournez macAddress = sb.toString().trim().toUpperCase(); else { // Obtenez l'adresse MAC de l'IP non locale try { System.out.println(ipAddress); Process p = Runtime.getRuntime() .exec("nbtstat -A " + ipAddress); ("= ==process=="+p); InputStreamReader ir = new InputStreamReader(p.getInputStream()); 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 } } br.close(); ir.close(); } catch (IOException ex) { } return macAddress } }
Jetons un coup d'œil à la deuxième méthode :
package com.alpha.test; importer java.io.BufferedReader; importer java.io.IOException; importer java.io.InputStream; importer java.io.InputStreamReader; importer java.io.LineNumberReader; classe publique GetMac {/** * java obtient l'adresse MAC de la carte réseau client * * @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 .Récupérer l'adresse IP du client (celle-ci doit être passée du client en arrière-plan) : // Sous la page jsp, c'est très simple, request.getRemoteAddr();// Étant donné que la couche VIew du système est implémentée avec JSF, des requêtes similaires ne peuvent pas être obtenues directement sur la page, donc une conversion forcée est effectuée dans le 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. Obtenez l'adresse MAC du client // Appelez la commande window , dans le Bean d'arrière-plan, obtenez l'adresse MAC via IP. La méthode est la suivante : // Vitesse d'exécution [rapide] 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("Adresse physique")) > 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("Impossible d'obtenir l'adresse MAC!");return null;}return mac;}//Vitesse d'exécution [lente] public String getMAC(String ip) {String str = null;String macAddress = null ;essayez {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("Adresse MAC ") > 1) {macAddress = str.substring(str.indexOf("MAC Address") + 14);break;}}}} catch (IOException e) {e.printStackTrace(System.out);return null;}return macAddress;}}
Troisième méthode, plus simple
importer java.io.IOException; importer java.io.InputStreamReader; importer java.io.LineNumberReader; public class MACAddress { String ip; String public MACAddress (String ip) { this.ip = ip } public MACAddress () { this.ip = "0.0.0.0"; } public String getMac(){ try { Processus p = Runtime.getRuntime().exec("arp -n"); InputStreamReader ir = new InputStreamReader(p.getInputStream()); LineNumberReader input = new LineNumberReader(ir); = "(" + this.ip + ")"; while(flag) { String str = input.readLine(); null) { if (str.indexOf(ipStr) > 1) { int temp = str.indexOf("at"); this.mac = str.substring( temp + 3, temp + 20 } } else break; = false; } } catch (IOException | InterruptedException e) { e.printStackTrace(System.out } return this.mac } public void setIp(String ip){ ceci.ip = ip; }}
Enfin, il faut agrandir le mouvement, les amis, surveillez attentivement.
La première chose à dire est la suivante : cette méthode peut prendre en charge l’obtention de l’adresse MAC de la machine réseau externe.
J'en avais un qui ne pouvait accéder qu'au réseau local. Vous ne pouvez pas y accéder si vous disposez d'un pare-feu, mais vous n'avez pas à vous en soucier.
J'ai testé l'adresse IP de Baidu et je peux obtenir l'adresse Mac.
Java obtient l'adresse Mac via IP - bloquer l'adresse IP bloquer l'adresse Mac
importer java.io.BufferedReader; importer java.io.InputStreamReader; importer java.util.regex.Matcher; importer java.util.regex.Pattern;/*** Obtenir l'adresse MAC* @author* 2011-12*/classe publique GetMacAddress { public static String callCmd(String[] cmd) { String result = ""; String line = ""; try { Processus proc = Runtime.getRuntime().exec(cmd); InputStreamReader is = new InputStreamReader(proc.getInputStream()); BufferedReader br = new BufferedReader (est); += ligne; } } catch(Exception e) { e.printStackTrace( } return result } /** * * @param; cmd première commande* @param une autre deuxième commande* @retourne le résultat de l'exécution de la deuxième commande*/ public static String callCmd(String[] cmd,String[] another) { String result = ""; String line = ""; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd); proc.waitFor(); //La première commande a été exécutée et la deuxième commande a été exécutée proc = rt.exec(un autre); InputStreamReader is = new InputStreamReader(proc.getInputStream()); } } catch(Exception e) { e.printStackTrace(); } return result } /** * * @param ip; Adresse IP cible, généralement dans le réseau local* @param sourceString La chaîne de résultat du traitement des commandes* @param macSeparator symbole de séparateur mac* @adresse mac de retour, représentée par le symbole séparateur ci-dessus*/ public static String filterMacAddress(final String ip, final String sourceString ,final String macSeparator) { String result = ""; String regExp = "((([0-9,AF,af]{1,2}" + macSeparator + "){1,5})[0-9,AF,af]{1,2})"; Modèle pattern = Pattern.compile(regExp); Matcher = pattern.matcher(sourceString); ()){ résultat = matcher.group(1); if(sourceString.indexOf(ip) <= sourceString.lastIndexOf(matcher.group(1))) { break; //S'il y a plusieurs IP, seul le Mac correspondant à cette IP correspond. } } return result } /** * * @param ip target ip * @return Mac Address * */ public static String getMacInWindows(final String ip ){ String result = ""; String[] cmd = { "cmd", "/c", "ping " + ip }; String[] autre = { "cmd", "/c", "arp -a" }; Chaîne cmdResult = callCmd(cmd,another); result = filterMacAddress(ip,cmdResult,"-"); return result; } /** * @param ip target 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; } /** * Obtenir l'adresse MAC* @return Renvoie l'adresse MAC*/ public static String getMacAddress(String ip){ String macAddress = "" macAddress = getMacInWindows(ip).trim(); if(macAddress==null||"".equals(macAddress)){ macAddress = getMacInLinux(ip).trim(); } return macAddress } //Faire un test public static void main(String[] args) { System .out.println(getMacAddress("220.181.111.148")); } }