避免使用InetAddress - 以网络字节顺序获取原始IP地址 [英] Avoid using InetAddress - Getting a raw IP address in network byte order

查看:167
本文介绍了避免使用InetAddress - 以网络字节顺序获取原始IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Google App Engine上使用MaxMind GeoLite国家/地区数据库。但是,我很难让Java API工作,因为它依赖于App Engine上无法使用的InetAddress类。

I am trying to use the MaxMind GeoLite Country database on the Google App Engine. However, I am having difficulty getting the Java API to work as it relies on the InetAddress class which is not available to use on the App Engine.

然而,我不是确定是否有一个简单的解决方法,因为它看起来只使用InetAddress类来确定给定主机名的IP。在我的情况下,主机名始终是IP。

However, I am not sure if there is a simple workaround as it appears it only uses the InetAddress class to determine the IP of a given hostname. In my case, the hostname is always an IP anyway.

我需要的是将表示为String的IP地址转换为网络字节顺序的字节数组(InetAddress类的addr.getAddress()方法提供)。

What I need is a way to convert an IP address represented as a String into a byte array of network byte order (which the addr.getAddress() method of the InetAddress class provides).

这是当前API使用的代码,我需要找到一种删除所有引用到InetAddress,同时确保它仍然有效!

This is the code the current API uses, I need to find a way of removing all references to InetAddress whilst ensuring it still works!

感谢您的宝贵时间。

/**
 * Returns the country the IP address is in.
 *
 * @param ipAddress String version of an IP address, i.e. "127.0.0.1"
 * @return the country the IP address is from.
 */
public Country getCountry(String ipAddress) {
    InetAddress addr;
    try {
        addr = InetAddress.getByName(ipAddress);
    } catch (UnknownHostException e) {
        return UNKNOWN_COUNTRY;
    }
    return getCountry(bytesToLong(addr.getAddress()));
}


推荐答案

// note: this is ipv4 specific, and i haven't tried to compile it.
long ipAsLong = 0;
for (String byteString : ipAddress.split("\\."))
{
    ipAsLong = (ipAsLong << 8) | Integer.parseInt(byteString);
}

这篇关于避免使用InetAddress - 以网络字节顺序获取原始IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆