Convert IP between IPv4 and numerical format in java

后端 未结 4 1329
猫巷女王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: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();
    

提交回复
热议问题