在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

根据IP地址获取用户的MAC地址Java代码

2016-12-20 13:16| 发布者: zhangjf| 查看: 496| 评论: 0

摘要: 根据IP地址获取用户的MAC地址 代码 /** * 根据IP地址获取mac地址 * @param ipAddress 127.0.0.1 * @return * @throws SocketException * @throws UnknownHostException */ p ...
根据IP地址获取用户的MAC地址

[Java]代码
  1. /**
  2. * 根据IP地址获取mac地址
  3. * @param ipAddress 127.0.0.1
  4. * @return
  5. * @throws SocketException
  6. * @throws UnknownHostException
  7. */
  8. public static String getLocalMac(String ipAddress) throws SocketException,
  9. UnknownHostException {
  10. // TODO Auto-generated method stub
  11. String str = "";
  12. String macAddress = "";
  13. final String LOOPBACK_ADDRESS = "127.0.0.1";
  14. // 如果为127.0.0.1,则获取本地MAC地址。
  15. if (LOOPBACK_ADDRESS.equals(ipAddress)) {
  16. InetAddress inetAddress = InetAddress.getLocalHost();
  17. // 貌似此方法需要JDK1.6。
  18. byte[] mac = NetworkInterface.getByInetAddress(inetAddress)
  19. .getHardwareAddress();
  20. // 下面代码是把mac地址拼装成String
  21. StringBuilder sb = new StringBuilder();
  22. for (int i = 0; i < mac.length; i++) {
  23. if (i != 0) {
  24. sb.append("-");
  25. }
  26. // mac[i] & 0xFF 是为了把byte转化为正整数
  27. String s = Integer.toHexString(mac[i] & 0xFF);
  28. sb.append(s.length() == 1 ? 0 + s : s);
  29. }
  30. // 把字符串所有小写字母改为大写成为正规的mac地址并返回
  31. macAddress = sb.toString().trim().toUpperCase();
  32. return macAddress;
  33. } else {
  34. // 获取非本地IP的MAC地址
  35. try {
  36. System.out.println(ipAddress);
  37. Process p = Runtime.getRuntime()
  38. .exec("nbtstat -A " + ipAddress);
  39. System.out.println("===process=="+p);
  40. InputStreamReader ir = new InputStreamReader(p.getInputStream());
  41. BufferedReader br = new BufferedReader(ir);
  42. while ((str = br.readLine()) != null) {
  43. if(str.indexOf("MAC")>1){
  44. macAddress = str.substring(str.indexOf("MAC")+9, str.length());
  45. macAddress = macAddress.trim();
  46. System.out.println("macAddress:" + macAddress);
  47. break;
  48. }
  49. }
  50. p.destroy();
  51. br.close();
  52. ir.close();
  53. } catch (IOException ex) {
  54. }
  55. return macAddress;
  56. }
  57. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 11:24

Copyright 2015-2025 djqfx

返回顶部