Basic knowledge point
IP-> integer:
Convert the IP address into byte array through the left shift (<<), (&), or (|) these operations to int to int
Integer-> IP:
Right shift operation (>>>), shift the right to 24 bits, and then perform the operator (&) 0xff. The obtained number is the first IP.
Right shift operation (>>>), shift 16 bits right, and then perform the operator (&) 0xff. The number obtained is the second IP.
Right shift operation (>>>), move to the right of 8 bits, and then perform the operator (&) 0xff. The number obtained is the third segment IP.
The integer value is performed with the operator (&) 0xff, and the number obtained is the fourth stage IP.
Thinking
IP address to INT type, for example, IP is "192.168.1.116", which is equivalent to "." "Divide the IP address into 4 parts, and the corresponding power value of each part is 256^3, 256^2, 256, 1, and when it is complex, it is as soon as possible. Can
INT type to IP address, similar ideas, except for weight value, but some string operations
Code
#include <STDIO.H> #include <STDLIB.H> #Include <string.h> #include <math.h> #Define len 16 TypeDef UNSIGNED Int 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 ;} / ***inverse string* / void swapstr (char*str, int begin, int end) {int i, j; for (i = begin, j = end; i <= j; i ++, I ++, i <= j; j -) {if (str [i]! = STR [J]) {str [i] = str [i] ^ str [j]; str [j] = str [i] ^ str [j]; str [i] = str [i] ^ str [j];}}} / ***ipstan string* / 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, 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; uILE ipInt; space ("%s"%s scanf ("%s scanf ("%s s "%s scanf ("%s s "%s scanf ("%s scanf ("%s s"%s scanf ("%s s"%s scanf ("%s s. ", ipstr)! = EOF) {ipint = iptint (ipstr); propf ("%u/n ", ipint); new = iptstr (ipint); Printf ("%s/n ", new);} Return 0 ;}