Java converts IP strings to integers

From , 5 Years ago, written in Java, viewed 78 times.
URL https://pastebin.vip/view/9cf742e9
  1. /**
  2.  * @author SunChong
  3.  */
  4. public class IpUtil {
  5.        
  6.         /**
  7.          * 将字符串型ip转成int型ip
  8.          * @param strIp
  9.          * @return
  10.          */
  11.         public static int Ip2Int(String strIp){
  12.                 String[] ss = strIp.split("\\.");
  13.                 if(ss.length != 4){
  14.                         return 0;
  15.                 }
  16.                 byte[] bytes = new byte[ss.length];
  17.                 for(int i = 0; i < bytes.length; i++){
  18.                         bytes[i] = (byte) Integer.parseInt(ss[i]);
  19.                 }
  20.                 return byte2Int(bytes);
  21.         }
  22.         /**
  23.          * 将int型ip转成String型ip
  24.          * @param intIp
  25.          * @return
  26.          */
  27.         public static String int2Ip(int intIp){
  28.                 byte[] bytes = int2byte(intIp);
  29.                 StringBuilder sb = new StringBuilder();
  30.                 for(int i = 0; i < 4; i++){
  31.                         sb.append(bytes[i] & 0xFF);
  32.                         if(i < 3){
  33.                                 sb.append(".");
  34.                         }
  35.                 }
  36.                 return sb.toString();
  37.         }
  38.        
  39.         private static byte[] int2byte(int i) {
  40.         byte[] bytes = new byte[4];
  41.         bytes[0] = (byte) (0xff & i);
  42.         bytes[1] = (byte) ((0xff00 & i) >> 8);
  43.         bytes[2] = (byte) ((0xff0000 & i) >> 16);
  44.         bytes[3] = (byte) ((0xff000000 & i) >> 24);
  45.         return bytes;
  46.     }
  47.         private static int byte2Int(byte[] bytes) {
  48.         int n = bytes[0] & 0xFF;
  49.         n |= ((bytes[1] << 8) & 0xFF00);
  50.         n |= ((bytes[2] << 16) & 0xFF0000);
  51.         n |= ((bytes[3] << 24) & 0xFF000000);
  52.         return n;
  53.     }
  54.        
  55.         public static void main(String[] args) {
  56.                 String ip1 = "192.168.0.1";
  57.                 int intIp = Ip2Int(ip1);
  58.                 String ip2 = int2Ip(intIp);
  59.                 System.out.println(ip2.equals(ip1));
  60.         }
  61. }
  62.  
  63. //java/5529

Reply to "Java converts IP strings to integers"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website