转:java 获取客户端ip mac地址

java 获取客户端ip mac地址
最近做一个安全系统,需要对用户的 ip 和 mac 地址进行验证,这里用到获取客户端ip和mac地址的两个方法,留存。

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值