开发者

Going from 127.0.0.1 to 2130706433, and back again

开发者 https://www.devze.com 2022-12-20 00:41 出处:网络
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 (开发者_运维技巧213

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"?


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()


You can also use the Google Guava InetAddress Class

String ip = "192.168.0.1";
InetAddress addr = InetAddresses.forString(ip);
// Convert to int
int address = InetAddresses.coerceToInteger(addr);
// Back to str 
String addressStr = InetAddresses.fromInteger(address));


I've modified my original answer. In Sun's implementation of InetAddress, the hashCode method produces the integer representation of the IPv4 address, but as the commenters correctly pointed out, this is not guaranteed by the JavaDoc. Therefore, I decided to use the ByteBuffer class to calculate the value of the IPv4 address instead.

import java.net.InetAddress;
import java.nio.ByteBuffer;

// ...

try {
    // Convert from integer to an IPv4 address
    InetAddress foo = InetAddress.getByName("2130706433");
    String address = foo.getHostAddress();
    System.out.println(address);

    // Convert from an IPv4 address to an integer
    InetAddress bar = InetAddress.getByName("127.0.0.1");
    int value = ByteBuffer.wrap(bar.getAddress()).getInt();
    System.out.println(value);

} catch (Exception e) {
    e.printStackTrace();
}

The output will be:

127.0.0.1
2130706433


In case you need to learn the long hand math, you can use Substr to rip out the octets. Mutliply the first octet signifying the Class by (256*256*256) or (2^24) second multiplied by (256*256) (2^16) third multiplied by (256) (2^8) fourth multiplied by 1 or (2^0)

127 * (2^24) + 0 *(2^16) + 0 * (2^8) + 1 * (2^0) 2130706432 + 0 + 0 + 1 = 2130706433


I've not tried it wrt. performance, but the simplest way is probably to use the NIO ByteBuffer.

e.g.

 byteBuffer.put(integer).array();

would return you a byte array representing the integer. You may need to modify the byte order.


Using the IPAddress Java library it is simple, one line of code for each direction. Disclaimer: I am the project manager of that library.

    IPv4Address loopback = new IPAddressString("127.0.0.1").getAddress().toIPv4();
    System.out.println(loopback.intValue());
    IPv4Address backAgain = new IPv4Address(loopback.intValue());
    System.out.println(backAgain);

Output:

    2130706433
    127.0.0.1


Another way:

public static long ipToLong(String ipAddress) {

    String[] ipAddressInArray = ipAddress.split("\\.");

    long result = 0;
    for (int i = 0; i < ipAddressInArray.length; i++) {

        int power = 3 - i;
        int ip = Integer.parseInt(ipAddressInArray[i]);
        result += ip * Math.pow(256, power);

    }

    return result;
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消