激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - java實現獲取用戶的MAC地址

java實現獲取用戶的MAC地址

2020-01-12 14:42hebedich JAVA教程

本文給大家匯總介紹了下使用java實現獲取客戶端用戶的MAC地址的方法,當然最后一種更全面一些,有需要的小伙伴們可以根據需求自由選擇。

方法一:將本機地址與局域網內其他機器區分開來

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
   * 根據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;
    }
  }

我們再來看下方法二:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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'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;
    }
}

方法三,更精簡一些

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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地址獲取。 

以前弄了一個只能訪問局域網。 有防火墻就訪問不了, 但是這個不用擔心了。
測試了百度的ip,已經可以獲得mac地址

java通過ip獲取mac地址-封ip封mac地址

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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"));
   }
  
}

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 在线成人免费观看www | 91精品国产乱码久久桃 | 欧美人的天堂一区二区三区 | 国产亚洲精品久久久久5区 99精品视频在线 | 中国一级免费视频 | 精品国产一区二区三区四区在线 | 国产精品一区二区三区在线 | 激情亚洲一区二区 | 99久久久精品国产一区二区 | 国产精品区一区二区三区 | 精品亚洲一| 狠狠久久伊人中文字幕 | 黄色高清av| 奶子吧naiziba.cc免费午夜片在线观看 | hd极品free性xxx一护士 | 一级片a| 日本高清在线免费 | 欧美日本色 | 久久久久久久久久久久久国产精品 | a免费视频 | 激情久久一区二区 | 色污视频| 一区二区三高清 | 欧美日韩免费看 | 人人舔人人射 | 亚洲最大av网站 | 综合网天天射 | 长泽雅美av | 一级大黄毛片 | 成人毛片一区二区三区 | 久久精品无码一区二区三区 | 欧美爱爱视频免费看 | 国产精品久久久久久久成人午夜 | 欧美成人三级视频 | 高清成人在线 | 久久激情国产 | 一级成人欧美一区在线观看 | 爱唯侦察 国产合集 亚洲 | 深夜影院一级毛片 | 91av资源在线 | 日本网站一区 |