日期:2014-05-16  浏览次数:20416 次

Java/JSP获得客户端网卡MAC地址的三种方法解析(附:获得真实IP)

Java/JSP获得客户端网卡MAC地址的三种方法解析

从网上查找资料java/jsp获得客户端(IE)网卡MAC地址的方法大概有三种。

1、通过命令方式,在客户端执行Ipconfig 等等。(java/jsp)

2、通过ActiveX的方法。(jsp)

3、通过向137的端口发送查询指令的方法。(java/jsp)

?

简介:

第一种方法,在真正用到时候不知道为什么获得mac地址的指令阻塞了,不往下继续执行。而且速度是这三种方法中最慢的一种。

代码如下:

String sip="";
String smac="";
sip = request.getHeader("x-forwarded-for");
if(sip == null ||sip.length() == 0 || "unknown".equalsIgnoreCase(sip))
{
sip = request.getHeader("proxy-Client-IP");
}
if (sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip))?
{
??? sip = request.getHeader("WL-Proxy-Client-IP");
}?
if (sip == null ||sip.length() == 0 || "unknown".equalsIgnoreCase(sip))?
{
??? sip = request.getRemoteAddr();
}

??? if(!"127.0.0.1".equals(sip)) //本机过滤掉
?? {
?????? Process process = Runtime.getRuntime().exec("nbtstat -a " + sip);
?????? InputStreamReader ir = new InputStreamReader(process.getInputStream());
??? LineNumberReader input = new LineNumberReader(ir);
??? String line;
while ((line = input.readLine()) != null)
????? if (line.indexOf("MAC Address") > 0)?
?? {
????????? smac = line.substring(line.indexOf("-") - 2);
?? }

?

第二种方法是用ActiveX来获得,速度比第一种方法快但是必须降低安全设置否则脚本不被执行

IE设置如下

1.打开IE浏览器
2.工具->Internet选项->安全
3.自定义级别(C)...
4.设置中对未标记为可安全执行脚本的ActiveX控件初始化并执行脚本
?? 选中启动(不安全)->每次不用点击"是"按钮,推荐,当然你的机器不能上互联网否则会有安全问题。
?? 选中提示->每次都得点击"是"按钮。
5.点击"确定"->"确定"按钮
6.重新启动IE浏览器设置生效

?

代码

<SCRIPT language=JScript event="OnCompleted(hResult,pErrorObject, pAsyncContext)" for=foo>
document.forms[0].userMacAddr.value=unescape(MACAddr);
</SCRIPT>
<SCRIPT language=JScript event=OnObjectReady(objObject,objAsyncContext) for=foo>
?? if(objObject.IPEnabled != null && objObject.IPEnabled != "undefined" && objObject.IPEnabled == true)
?? {
??? if(objObject.MACAddress != null && objObject.MACAddress != "undefined")
??? MACAddr = objObject.MACAddress;
??? }
</SCRIPT>
<META content="MSHTML 6.00.2800.1106" name=GENERATOR>
...

<body>
<OBJECT id=locator classid=CLSID:76A64158-CB41-11D1-8B02-00600806D9B6 VIEWASTEXT></OBJECT>
<OBJECT id=foo classid=CLSID:75718C9A-F029-11d1-A1AC-00C04FB6C223></OBJECT>
<SCRIPT language=JScript>
?? var service = locator.ConnectServer();
?? var MACAddr ;
?? service.Security_.ImpersonationLevel=3;
?? service.InstancesOfAsync(foo, 'Win32_NetworkAdapterConfiguration');
</SCRIPT>
...??????? <td height="20" align="center">标 识:</td>
<td><input value="no" name="userMacAddr" size="20" style="width:150px" readonly="yes"></td>

?

第三种方法是用UDP协议来发送查询mac指令然后返回值中解析mac。个人认为这是最好的方法(暂时)速度最快

?

<%
String smac = "";
String sip = request.getHeader("x-forwarded-for");???
if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {???
??? sip = request.getHeader("Proxy-Client-IP"