방법 1: 로컬 컴퓨터 주소를 LAN의 다른 컴퓨터와 구별
/** * IP 주소를 기반으로 MAC 주소를 가져옵니다. * @param ipAddress 127.0.0.1 * @return * @throws SocketException * @throws UnknownHostException */ public static String getLocalMac(String ipAddress) throws SocketException, UnknownHostException { // TODO 자동 생성된 메소드 스텁 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 바이트를 양의 정수로 변환합니다. String s = Integer.toHexString(mac[i] & 0xFF) sb.append(s.length() == 1 ? 0 + s : s); 소문자를 대문자로 변경하여 일반 mac 주소로 만들고 return macAddress = sb.toString().trim().toUpperCase(); else { // 로컬이 아닌 IP의 MAC 주소를 가져옵니다. try { System.out.println(ipAddress); Process p = Runtime.getRuntime() .exec("nbtstat -A " + ipAddress); ("= ==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) } } br.close(); ir.close(); } catch (IOException ex) { } return macAddress } }
두 번째 방법을 살펴보겠습니다.
패키지 com.alpha.test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.LineNumberReader;public 클래스 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로 구현되어 있기 때문에 유사한 요청을 페이지에서 직접 얻을 수 없으므로 // public String getMyIP() {// try {// FacesContext fc = FacesContext Bean에서 강제 변환이 이루어집니다. getCurrentInstance ();// HttpServletRequest 요청 = (HttpServletRequest) fc// .getExternalContext().getRequest();// 반환 request.getRemoteAddr();// } catch (Exception e) {// e.printStackTrace();// }// return "";// }// 2. 클라이언트 mac 주소 가져오기 // 창 명령 호출 , 백그라운드 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 (메시지 != null) {if ((index = message.indexOf("물리적 주소")) > 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("mac 주소를 가져올 수 없습니다!");return null;}return mac;}//실행 속도 [slow] 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 주소) ") > 1) {macAddress = str.substring(str.indexOf("MAC 주소") + 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 } 공개 MACAddress() this.ip = "0.0.0.0"; } public String getMac(){ try { 프로세스 p = Runtime.getRuntime().exec("arp -n"); InputStreamReader(p.getInputStream()); LineNumberReader input = new LineNumberReader(ir); String ipStr = "(" + 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); = false; } } catch (IOException | InterruptedException e) { e.printStackTrace(System.out) } return this.mac } public void setIp(String ip); this.ip = }}
마지막으로, 우리는 움직임을 확대해야 합니다, 여러분, 주의깊게 지켜보세요.
가장 먼저 말해야 할 것은 이 방법은 외부 네트워크 시스템의 MAC 주소 획득을 지원할 수 있다는 것입니다.
예전에는 LAN에만 액세스할 수 있는 장치가 있었습니다. 방화벽이 설치되어 있으면 접속이 불가능하지만, 이에 대해서는 걱정하지 않으셔도 됩니다.
Baidu의 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 클래스 GetMacAddress { public static String callCmd(String[] cmd) { String result = "" String line = "" try { 프로세스 proc = Runtime.getRuntime().exec(cmd); InputStreamReader is = new InputStreamReader(proc.getInputStream()); BufferedReader br = new BufferedReader (is) while ((line = br.readLine ()) != null) += line; } } catch(Exception e) { e.printStackTrace() } 반환 결과 } /** * * @param; cmd 첫 번째 명령* @param 또 다른 두 번째 명령* @return 두 번째 명령의 실행 결과*/ public static String callCmd(String[] cmd,String[] another) { String result = ""; String line = ""; 런타임 rt = Runtime.getRuntime(); 프로세스 proc = rt.exec(cmd); proc.waitFor(); //첫 번째 명령이 실행되고 두 번째 명령이 실행되었습니다. 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(); } 반환 결과 } /** * * @param ip 일반적으로 LAN 내의 대상 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,AF,af]{1,2}" + macSeparator + "){1,5})[0-9,AF,af]{1,2})"; 패턴 패턴 = Pattern.compile(regExp); 일치자 matcher = Pattern.matcher(sourceString); ()){ 결과 = matcher.group(1); if(sourceString.indexOf(ip) <= sourceString.lastIndexOf(matcher.group(1))) { break; //IP가 여러 개인 경우 해당 IP에 해당하는 Mac만 일치합니다. } } return result; /** * * @param ip target ip * @return Mac Address * */ public static String getMacInWindows(final String ip ){ 문자열 결과 = ""; String[] cmd = { "cmd", "/c", "ping " + ip } String[] another = { "cmd", "/c", "arp -a" }; 끈 cmdResult = callCmd(cmd,another); result = filterMacAddress(ip,cmdResult,"-"); return result; /** * @param ip target ip * @return Mac Address * */ public static String getMacInLinux(최종 문자열) ip){ 문자열 결과 = ""; 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) { 시스템 .out.println(getMacAddress("220.181.111.148"));