찾다
Javajava지도 시간MAC 사용자 IP를 얻는 여러 가지 예제 방법

이 글에서는 주로 JAVA에서 사용자의 MAC 주소를 얻는 방법의 다양한 예를 소개합니다. 필요한 친구는

사용자의 MAC 주소를 얻는 Java 방법:

을 참조하세요.

방법 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 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;
  }
 }

방법 2를 살펴보겠습니다.

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&#39;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;
  }
}

3번째 방법이 더 간편합니다.

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 주소.

저는 LAN에만 접속할 수 있는 것을 가지고 있었습니다. 방화벽이 설치되어 있으면 접근이 불가능하지만, 이에 대해서는 걱정하지 않으셔도 됩니다.

Baidu의 IP를 테스트했으며 이미 mac 주소를 얻을 수 있습니다

java는 ip를 통해 mac 주소를 얻습니다. - block ip block mac address

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. Java 무료 동영상 튜토리얼

2. JAVA 튜토리얼 매뉴얼

3.Java 주석 종합 분석

위 내용은 MAC 사용자 IP를 얻는 여러 가지 예제 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까?고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까?Mar 17, 2025 pm 05:46 PM

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

적절한 버전 및 종속성 관리로 Custom Java 라이브러리 (JAR Files)를 작성하고 사용하려면 어떻게해야합니까?적절한 버전 및 종속성 관리로 Custom Java 라이브러리 (JAR Files)를 작성하고 사용하려면 어떻게해야합니까?Mar 17, 2025 pm 05:45 PM

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까?카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까?Mar 17, 2025 pm 05:44 PM

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까?캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까?Mar 17, 2025 pm 05:43 PM

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까?Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까?Mar 17, 2025 pm 05:35 PM

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경