Going from 127.0.0.1 to 2130706433, and back again

2020-01-25 07:40发布

Using the standard Java libraries, what is the quickest way to get from the dotted string representation of an IPV4-address ("127.0.0.1") to the equivalent integer representation (2130706433).

And correspondingly, what is the quickest way to invert said operation - going from the integer 2130706433 to the string representation"127.0.0.1"?

7条回答
▲ chillily
2楼-- · 2020-01-25 08:09

String to int:

int pack(byte[] bytes) {
  int val = 0;
  for (int i = 0; i < bytes.length; i++) {
    val <<= 8;
    val |= bytes[i] & 0xff;
  }
  return val;
}

pack(InetAddress.getByName(dottedString).getAddress());

Int to string:

byte[] unpack(int bytes) {
  return new byte[] {
    (byte)((bytes >>> 24) & 0xff),
    (byte)((bytes >>> 16) & 0xff),
    (byte)((bytes >>>  8) & 0xff),
    (byte)((bytes       ) & 0xff)
  };
}


InetAddress.getByAddress(unpack(packedBytes)).getHostAddress()
查看更多
登录 后发表回答