Java - 获取本机IP或者请求用户的真正的IP地址

一、在Web请求中获取请求用户的真正IP:

public static String getUserRealIP(HttpServletRequest request) throws UnknownHostException {

        

        String ip = "";

        

        // 有的user可能使用代理,为处理用户使用代理的情况,使用x-forwarded-for

        if  (request.getHeader("x-forwarded-for") == null)  {

            ip = request.getRemoteAddr();

        }  else  {

            ip = request.getHeader("x-forwarded-for");

        }

        

        if  ("127.0.0.1".equals(ip))  {

            // 获取本机真正的ip地址

            ip = InetAddress.getLocalHost().getHostAddress();

        }

        

        return ip;

    } 

二、获取本机ip地址和主机名:

import java.util.*;

import java.net.*;

public class getMyIP

{

public static void main(String[] args) {

String ip = null;

String host = null;

try{

InetAddress ia = InetAddress.getLocalHost(); 

host = ia.getHostName();//获取计算机名字

ip = ia.getHostAddress();//获取IP

    } catch(UnknownHostException e) {

e.printStackTrace();

}

System.out.println(host);

System.out.println(IP);

}

}

猜你喜欢

转载自josh-persistence.iteye.com/blog/1886456