首先要獲得ip地址:
根據客戶端的http請求,利用request.getRemoteAddr()獲取客戶端Ip地址。在局域網內getRemoteAddr()和getRemoteHost()獲得的結果相同。request.getRemoteAddr()是獲得客戶端的ip地址 。getRemoteHost()是獲得客戶端的主機名 。在有些場景中,可能有Squid等反向代理軟件就不能獲取到客戶端的真實IP地址了。
經過代理以後,由於在客戶端和服務之間增加了中間層,因此服務器無法直接拿到客戶端的IP,服務器端應用也無法直接通過轉發請求的地址返回給客戶端。但是在轉發請求的HTTP頭信息中,增加了X-FORWARDED-FOR信息。用以跟蹤原有的客戶端IP地址和原來客戶端請求的服務器地址。當我們訪問http://www.letu.com/index.jsp/ 時,其實並不是我們瀏覽器真正訪問到了服務器上的index.jsp文件,而是先由代理服務器去訪問http://159.226.94.32/index.jsp ,代理服務器再將訪問到的結果返回給我們的瀏覽器,因爲是代理服務器去訪問index.jsp的,所以index.jsp中通過request.getRemoteAddr()的方法獲取的IP實際上是代理服務器的地址,並不是客戶端的IP地址。
//獲取ip地址
public String getIpAddr(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;
}
獲取mac地址:
我們用ARP -n 列出詳細信息。
[root@centos-5 bin]# arp -n
Address HWtype HWaddress Flags Mask Iface
159.226.94.126 ether A4:56:30:D3:5D:43 C eth0
獲取mac的java 代碼:import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
public class MACAddress {
String ip;
String mac;
public MACAddress (String ip){
this.ip = ip;
}
public MACAddress (){
this.ip = "0.0.0.0";
}
public String getMac(){
try {
Process p = Runtime.getRuntime().exec("arp -n");
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
p.waitFor();
boolean flag = true;
String ipStr = "(" + this.ip + ")";
while(flag) {
String str = input.readLine();
if (str != null) {
if (str.indexOf(ipStr) > 1) {
int temp = str.indexOf("at");
this.mac = str.substring(
temp + 3, temp + 20);
break;
}
} else
flag = false;
}
} catch (IOException | InterruptedException e) {
e.printStackTrace(System.out);
}
return this.mac;
}
public void setIp(String ip){
this.ip = ip;
}
}
參考文檔:http://blog.sina.com.cn/s/blog_6c87374b01019nwk.html