---
title: "java 获取客户端ip mac地址"
author: "ariyue"
date: "2010-02-23T15:47:31Z"
tags: ["Bean", "JSF", "JSP", "Java", "Linux"]
categories: ["编程语言"]
slug: "java-ip-mac"
draft: false
lastmod: "2010-02-23T15:47:31Z"
id: 600828
url: "https://ariyue.iteye.com/blog/600828"
---

转自：http://hi.baidu.com/coolcode/blog/item/0d42ffde48e07e5094ee37ec.html/cmtid/10029f13f5f1b78b6538dbca

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 getMACAddress(String ip){
String str = "";
String macAddress = "";
try {
Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i < 100; i++) {
str = input.readLine();
if (str != null) {
if (str.indexOf("MAC Address") > 1) {
macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
break;
}
}
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
return macAddress;
}

补充：
关于获取IP地址的方式，最近在linux下有一个教训，如果单纯通过InetAddress来获取IP地址，就会出现在不同的机器上IP地址不同的问题。
InetAddress.getLocalHost().getAddress() 实际上是根据hostname来获取IP地址的。linux系统在刚刚装完默认的hostname是localhost，所以通过上面代码获取到的本机 ip就是127.0.0.1, 相对应，比如我的hostname就是rjlin.atsig.com 返回的ip地址确是atsig.com的地址。暂时采用下面代码来处理，当然还不够灵活：
public static byte[] getIp() throws UnknownHostException {
byte[] b = InetAddress.getLocalHost().getAddress();
Enumeration allNetInterfaces = null;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress ip = null;
NetworkInterface netInterface = null;
while (allNetInterfaces.hasMoreElements()) {
netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.getName().trim().equals("eth0")){
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
}
break;
}
}
if (ip != null && ip instanceof Inet4Address) {
return b = ip.getAddress();
}
return b;
}