【问题标题】:Avoid using InetAddress - Getting a raw IP address in network byte order避免使用 InetAddress - 以网络字节顺序获取原始 IP 地址
【发布时间】:2017-05-10 04:23:07
【问题描述】:

我正在尝试使用 Google App Engine 上的 MaxMind GeoLite Country 数据库。但是,我很难让 Java API 工作,因为它依赖 InetAddress 类,而该类在 App Engine 上不可用。

但是,我不确定是否有一个简单的解决方法,因为它似乎只使用 InetAddress 类来确定给定主机名的 IP。就我而言,主机名始终是 IP。

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

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

感谢您的宝贵时间。

/**
 * 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()));
}

【问题讨论】:

  • 抱歉代码格式,当我创建帖子时它看起来很好。所有的代码都在那里。

标签: java google-app-engine inetaddress


【解决方案1】:
// 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);
}

【讨论】:

  • 太棒了!它完美地工作。我认为您无法解释该代码的作用以及如何将其扩展为适用于 ipv6?非常感谢
  • 将其扩展为 ipv6 需要一些工作,因为 ipv6 地址中可能包含一系列 0。除此之外,ipv6 地址不适合 64 位(它们是 128 位长)。但是对于 ipv4 地址,它所做的是获取每一块,将结果向左移动 8 位(因为每一块代表一个字节,或 8 位),然后添加该块。
【解决方案2】:

GeoIPCountryWhois 数据库中的所有 12000 多个条目均采用以下形式:

"4.17.135.32","4.17.135.63","68257568","68257599","CA","Canada"

将您拥有的虚线四边形地址分解为子字符串并以这种方式检查它们。

【讨论】:

    猜你喜欢
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多