Going from 127.0.0.1 to 2130706433, and back again

我只是一个虾纸丫 提交于 2019-12-17 06:09:37

问题


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


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



回答2:


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



回答3:


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



回答4:


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




回答5:


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.




回答6:


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



回答7:


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;
  }


来源:https://stackoverflow.com/questions/2241229/going-from-127-0-0-1-to-2130706433-and-back-again

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!