A method that converts an IP address to an int using Java code

  • 2020-04-01 04:06:13
  • OfStack

Basic knowledge  
 
IP - > Integer:
Converts IP addresses into byte arrays
By left shift (< <) , and (&), or (|) are converted to int
Integer - > IP:
Shift the integer value to the right (> > >) , right move 24 bits, and then with the operator (&) 0xFF, the number is the first segment IP.
Shift the integer value to the right (> > >) , right 16 bits, and then with the operator (&) 0xFF, the number is the second IP segment.
Shift the integer value to the right (> > >) , 8 bits to the right, and then with the operator (&) 0xFF, the number is the third segment IP.
When the integer value is compared to the operator (&) 0xFF, the resulting number is the fourth segment IP.

Train of thought
IP address to int type, for example, IP is "192.168.1.116", equivalent to ". "IP address is divided into four parts, the corresponding weight of each part is 256^3, 256^2, 256, 1, each other can be

Int type to IP address, the idea is similar, can be divided by the weight, but there is part of the string operation


code


  #include <stdio.h> 
  #include <stdlib.h> 
  #include <string.h> 
  #include <math.h> 
   
  #define LEN 16 
   
  typedef unsigned int uint; 
   
   
  uint ipTint(char *ipstr) 
  { 
    if (ipstr == NULL) return 0; 
   
    char *token; 
    uint i = 3, total = 0, cur; 
   
    token = strtok(ipstr, "."); 
   
    while (token != NULL) { 
      cur = atoi(token); 
      if (cur >= 0 && cur <= 255) { 
        total += cur * pow(256, i); 
      } 
      i --; 
      token = strtok(NULL, "."); 
    } 
   
    return total; 
  } 
   
   
  void swapStr(char *str, int begin, int end) 
  { 
    int i, j; 
   
    for (i = begin, j = end; i <= j; i ++, j --) { 
      if (str[i] != str[j]) { 
        str[i] = str[i] ^ str[j]; 
        str[j] = str[i] ^ str[j]; 
        str[i] = str[i] ^ str[j]; 
      } 
    } 
  } 
   
   
  char* ipTstr(uint ipint) 
  { 
    char *new = (char *)malloc(LEN); 
    memset(new, '0', LEN); 
    new[0] = '.'; 
    char token[4]; 
    int bt, ed, len, cur; 
   
    while (ipint) { 
      cur = ipint % 256; 
      sprintf(token, "%d", cur); 
      strcat(new, token); 
      ipint /= 256; 
      if (ipint) strcat(new, "."); 
    } 
   
    len = strlen(new); 
    swapStr(new, 0, len - 1); 
   
    for (bt = ed = 0; ed < len;) { 
      while (ed < len && new[ed] != '.') { 
        ed ++; 
      } 
      swapStr(new, bt, ed - 1); 
      ed += 1; 
      bt = ed; 
    } 
   
    new[len - 1] = '0'; 
   
    return new; 
  } 
   
  int main(void) 
  { 
    char ipstr[LEN], *new; 
    uint ipint; 
   
    while (scanf("%s", ipstr) != EOF) { 
      ipint = ipTint(ipstr); 
      printf("%un", ipint); 
   
      new = ipTstr(ipint); 
      printf("%sn", new); 
    } 
   
    return 0; 
  } 


Related articles: