Convert IP between IPv4 and numerical format in java

后端 未结 4 1300
猫巷女王i
猫巷女王i 2021-01-05 14:46

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

4条回答
  •  鱼传尺愫
    2021-01-05 15:47

    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

提交回复
热议问题