0

I have a problem with InetAddress.getLocalHost().getHostAddress(). It works correctly on most machines, but it fails on one where there are more IP addresses available (in this case "the wrong" address belongs to VMware network adapter). I need the address to put it into a message (which then is used on the server as an address where a response should be sent).

I know that I may use NetworkInterface.getNetworkInterfaces() to get all network interfaces but how I may programatically find the right one which is later visible for the server? In my particular case both clients and the server are located inside the same corporate network.

4

2 回答 2

1

If all machines are in the same network and this network has its IP range, you may check if IP is in this range. Usually vmware network adapters have IPs in 192.168.0.x subnet - if your corporate range is different, then it should be enough.

于 2013-06-18T07:17:58.840 回答
0

也许下面的课程可以帮助 IP

public enum IpAddressHelper
{

    X_FORWARDED_FOR("X-Forwarded-For"),
    PROXY_CLIENT_IP("Proxy-Client-IP"),
    WL_PROXY_CLIENT_IP("WL-Proxy-Client-IP"),
    HTTP_CLIENT_IP("HTTP_CLIENT_IP"),
    HTTP_X_FORWARDED_FOR("HTTP_X_FORWARDED_FOR");

    private static final Logger LOGGER = LoggerFactory.getLogger(IpAddressHelper.class);
    private static final String REMOTE_ADDR = "REMOTE_ADDR";
    private String key;

    /**
     * @param key
     */
    IpAddressHelper(String key)
    {
        this.key = key;
    }

    /**
     * @return the key
     */
    public String getKey()
    {
        return key;
    }

    public static String getClientIpAddr(HttpServletRequest request)
    {

        String ip = null;
        for (IpAddressHelper header : IpAddressHelper.values())
        {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            {
                ip = request.getHeader(header.getKey());
                LOGGER.info("tried:" + header);
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    public static String getClientIpAddr(Map<String, String> requestHeaders)
    {
        String ip = null;
        for (IpAddressHelper header : IpAddressHelper.values())
        {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            {
                ip = requestHeaders.get(header.getKey());
                LOGGER.info("tried:" + header);
            }
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = requestHeaders.get(REMOTE_ADDR);
        }

        return ip;
    }
}
于 2013-06-18T07:18:53.903 回答