Convert IP between IPv4 and numerical format in ja

2020-03-21 10:03发布

An IPv4 can have more representations: as string (a.b.c.d) or numerical (as an unsigned int of 32 bits). (Maybe other, but I will ignore them.)

Is there any built in support in Java (8), simple and easy to use, without network access, to convert between these formats?

I need something like this:

long ip = toNumerical("1.2.3.4"); // returns 0x0000000001020304L
String ipv4 = toIPv4(0x0000000001020304L); // returns "1.2.3.4"

If there is no built in such functions in Java, feel free to suggest other solutions.

Thank you

标签: java ip ipv4
3条回答
SAY GOODBYE
2楼-- · 2020-03-21 10:14

Heres is a way to Convert IP to Number. I found it a valid way to accomplish the task in Java.

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

This is also how you would implement it in Scala.

  def convertIPToLong(ipAddress: String): Long = {

    val ipAddressInArray = ipAddress.split("\\.")
    var result = 0L

    for (i  <- 0  to ipAddressInArray.length-1) {
      val power = 3 - i
      val ip = ipAddressInArray(i).toInt
      val longIP = (ip * Math.pow(256, power)).toLong
      result = result +longIP
    }
    result
  }
查看更多
狗以群分
3楼-- · 2020-03-21 10:24

Code snippet provided by QuakeCore will throw "java.net.UnknownHostException: Unable to resolve host" on the part where you want to convert it back to string

but the idea of utilizing InetAddress class is correct. Here is what you want to do:

            try {
                InetAddress inetAddressOrigin = InetAddress.getByName("78.83.228.120");
                int intRepresentation = ByteBuffer.wrap(inetAddressOrigin.getAddress()).getInt(); //1314120824

                ByteBuffer buffer = ByteBuffer.allocate(4);
                buffer.putInt(intRepresentation);
                byte[] b = buffer.array();

                InetAddress inetAddressRestored = InetAddress.getByAddress(b);
                String ip = inetAddressRestored.getHostAddress();//78.83.228.120

            } catch (UnknownHostException e) {
                e.printStackTrace(); //
            }

P.S.: If you will do this for some list of ips, validate them to be sure they don't have subnet masks, for example: 78.83.228.0/8 In this case you will need to flatten them: 78.83.228.0/8 => 78.83.228.0 78.83.228.1 78.83.228.2 78.83.228.3 78.83.228.4 78.83.228.5 78.83.228.6 78.83.228.7

查看更多
走好不送
4楼-- · 2020-03-21 10:33

The can be done using InetAddress as follows.

   //Converts a String that represents an IP to an int.
   InetAddress i= InetAddress.getByName(IPString);
   int intRepresentation= ByteBuffer.wrap(i.getAddress()).getInt();

   //This convert an int representation of ip back to String
   i= InetAddress.getByName(String.valueOf(intRepresentation));
   String ip= i.getHostAddress();
查看更多
登录 后发表回答