Home Java javaTutorial Multiple example methods to obtain MAC user IP

Multiple example methods to obtain MAC user IP

May 05, 2017 pm 02:25 PM

This article mainly introduces various examples of JAVA methods to obtain the user's MAC address. Friends in need can refer to the following

java method to obtain the user's MAC address:

Method 1: Distinguish the local machine address from other machines in the 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;
  }
 }
Copy after login

Let’s look at method 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;
  }
}
Copy after login

Method three, more streamlined:

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;
 }
}
Copy after login

Finally, we have to enlarge the move, friends, please pay attention carefully

The first thing to say is: this method can Supports obtaining the mac address of external network machines.

I used to have one that could only access the LAN. You can't access it if you have a firewall, but you don't have to worry about this.

Tested Baidu’s ip and can already get the mac address

java obtains the mac address through ip-block ip and 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"));
  }
 }
Copy after login

[Related recommendations]

1. Java Free Video Tutorial

2. JAVA Tutorial Manual

3. Comprehensive Analysis of Java Annotations

The above is the detailed content of Multiple example methods to obtain MAC user IP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

No response when entering password on mac keyboard? No response when entering password on mac keyboard? Feb 20, 2024 pm 01:33 PM

Introduction: In this article, this website will introduce to you the relevant content about the Mac keyboard not responding when entering passwords. I hope it will be helpful to you, let’s take a look. How to solve the problem that the password cannot be entered on the Apple Mac system? You can also try to connect this keyboard to other computers to see if it works normally. If the same problem occurs on another computer, it's most likely a fault with the keyboard itself. You may consider replacing the keyboard or repairing it. The first time you log in to Alipay with your Mac computer, you will find the login interface and cannot enter your password. The password input field displays: "Please click here to install the control", so Alipay login requires the installation of security controls. Security controls can encrypt and protect the information you enter (amount, password, etc.) to improve account security. Tie

3 tips to easily customize your Mac computer name, host name and Bonjour name 3 tips to easily customize your Mac computer name, host name and Bonjour name Mar 06, 2024 pm 12:20 PM

Many Mac users tend to keep the default name of their device and may never consider changing it. Many people choose to stick with the name from the initial setup, such as "Johnny's MacBook Air" or simply "iMac." Learning how to change the name of your Mac is a very useful skill, especially when you have multiple devices, as it can help you quickly distinguish and manage them. Next, we will teach you step by step how to change the computer name, host name and Bonjour name (local host name) in macOS system. Why should you change your Mac name? Changing the name of your Mac can not only show your personality, but also help improve the user experience: Personalize your Mac: The default name may not be to your taste, change it to a name you like.

Forgot your mac installer password? Forgot your mac installer password? Feb 20, 2024 pm 01:00 PM

Introduction: In this article, this website will introduce to you the relevant content about forgetting the password of the Mac installation program. I hope it will be helpful to you, let’s take a look. What to do if you forget your password for Apple computer installation software. First, find iCloud in the phone settings and click to open it. Next, enter your account number and password. There is a line of small words below the login button that prompts you if you have forgotten your ID or password. Click this option. Normally, after you enter an incorrect password multiple times on the login interface, your MacBook Pro will prompt you to use your bound Apple ID to reset your password. You only need to follow the steps prompted by the system to complete the password reset. 3. First shut down your Mac, then restart it. While pressing the power button, immediately press and hold com on the keyboard.

pkg file to install on mac? pkg file to install on mac? Feb 20, 2024 pm 03:21 PM

Preface: Today, this site will share with you the relevant content about installing pkg files on Mac. If it can solve the problem you are facing now, don’t forget to follow this site and start now! The previous version of macos pkg cannot be installed to upgrade the operating system: If your laptop is using an older operating system version, it is recommended to upgrade to the latest operating system version. Because older versions may not support installation of the latest macOS system. Select "Erase" in Disk Utility, then select the Macos extension in the format, do not check the encryption option, and do not select the apfs format, and finally click the "Erase" button to solve the problem of being unable to complete the macOS installation. Drag the application's icon to the file starting with App

How to turn pages when typing on Apple Mac? How to turn pages when typing on Apple Mac? Feb 20, 2024 pm 12:54 PM

Introduction: Today, this site will share with you relevant content about how to turn pages when typing on Apple Mac. If it can solve the problem you are facing now, don’t forget to follow this site and start now! Tips for using the touchpad on Apple MacBook laptops. The steps for setting up two-finger sliding on Apple computers are as follows: Find the "Settings" icon on the computer desktop and click it. Select "Touchpad" in the settings interface, and then click "Scroll to Zoom". Check "Scroll direction: Natural" in the scroll zoom options to complete the setting. Setting up a two-finger swipe method on your Apple computer is easy. First, turn on your computer and click on the Settings icon at the top of the screen. In the settings interface, select the "Touchpad" option. Then click "Scroll Zoom" and make sure "Scroll Direction" is checked

How to set up WeChat Mac to automatically convert voice messages into text - How to set up voice to text conversion How to set up WeChat Mac to automatically convert voice messages into text - How to set up voice to text conversion Mar 19, 2024 am 08:28 AM

Recently, some friends have consulted the editor about how to set up WeChat Mac to automatically convert voice messages into text. The following is a method for setting up WeChat Mac to automatically convert voice messages into text. Friends in need can come and learn more. Step 1: First, open the Mac version of WeChat. As shown in the picture: Step 2: Next, click &quot;Settings&quot;. As shown in the picture: Step 3: Then, click &quot;General&quot;. As shown in the picture: Step 4: Then check the option &quot;Automatically convert voice messages in chat to text&quot;. As shown in the picture: Step 5: Finally, close the window. As shown in the picture:

Can Mac cut files to hard drive? Can Mac cut files to hard drive? Feb 20, 2024 pm 01:00 PM

Introduction: This article is here to introduce you to the relevant content of cutting files to the hard disk on Mac. I hope it will be helpful to you, let’s take a look. How to Export Photos to a Mobile Hard Drive on a Mac Computer You can use the Finder or Photos application to export photos to a mobile hard drive. When using Finder to export photos, first make sure the mobile hard drive is connected to the Mac and is successfully recognized by the Mac. The steps to transfer photos from Mac to hard drive are simple: first, connect the mobile hard drive to the computer, and then open the [Launcher] icon. Then, find and click the [Photos] icon in the pop-up window. In the opened [Photos] window, hold down the [Shift] key

Mac black apple boot method? Mac black apple boot method? Feb 20, 2024 pm 01:00 PM

Preface: This article is here to introduce you to the relevant content about the mac black apple boot method. I hope it will be helpful to you, let’s take a look. Black Apple OC boot quick configuration tutorial 1. After entering the loverconfigurator software interface, click on the "Boot Parameters" setting. The default boot volume name is set to the disk name that was erased when installing the Black Apple system. But Benjuannai? 0, then click Save in the lower right corner, restart the computer, and replace the lover boot interface with the Apple logo boot interface. Secure Boot effectively prevents unsigned bootloaders from booting from any internal disk or USB drive. However, Clover or OC boot does not support the secure boot function. To start

See all articles