获取发送请求的机器ip相关代码:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();//返回请求行中的资源名称
String url = request.getRequestURL().toString();//获得客户端发送请求的完整url
String ip = request.getRemoteAddr();//返回发出请求的IP地址
String params = request.getQueryString();//返回请求行中的参数部分
String host=request.getRemoteHost();//返回发出请求的客户机的主机名
int port =request.getRemotePort();//返回发出请求的客户机的端口号。
}
获取本机ip地址
private String getHostIP(){
String tempIP = “127.0.0.1”;
try {
tempIP = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(tempIP);
try{
Enumeration networks = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
Enumeration addrs;
while (networks.hasMoreElements())
{
addrs = networks.nextElement().getInetAddresses();
while (addrs.hasMoreElements())
{
ip = addrs.nextElement();
if (ip != null
&& ip instanceof Inet4Address
&& ip.isSiteLocalAddress()
&& !ip.getHostAddress().equals(tempIP))
{
return ip.getHostAddress();
}
}
}
return tempIP;
} catch(Exception e){
throw new RuntimeException(e);
}
}