作者:手机用户2502908547 | 来源:互联网 | 2024-12-16 08:49
在开发Web应用时,有时需要获取客户端的IP地址以及MAC地址来增强系统的安全性和功能性。本文将通过一个简单的Java Servlet实例来展示如何实现这一功能。
package com.example.servlets;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ClientInfoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String clientIp = getClientIpAddress(request);
String clientMac = getMACAddress(clientIp);
System.out.println("Client IP: " + clientIp);
System.out.println("Client MAC: " + clientMac);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println(" ");
out.println(" ");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" ");
out.println("");
out.flush();
out.close();
}
private String getClientIpAddress(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
private 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;
}
}
以上代码展示了如何在Java Servlet中获取客户端的IP地址和MAC地址。首先,通过请求头信息尝试获取客户端的真实IP地址,如果这些头信息不存在或无效,则使用HttpServletRequest的getRemoteAddr方法作为备选方案。对于MAC地址的获取,通过执行命令行工具nbtstat来查询指定IP地址对应的MAC地址,并从命令输出中解析出MAC地址。
需要注意的是,这种方法依赖于操作系统的命令行工具,可能在不同的操作系统上表现不同。此外,获取客户端MAC地址通常仅限于局域网环境,在广域网环境下可能无法实现,因为大多数网络设备会隐藏或更改客户端的真实MAC地址以保护用户隐私。