ipアドレスを整数整数に変換してIPアドレスに変換

1862 ワード

1.IPアドレスを整数に変換
intipstrtoint(const char *ip) { int   result = 0; int   tmp = 0; int   shift = 24; const char *pEnd = ip; const char *pStart = ip; while(*pEnd != '\0') { while(*pEnd != '.' && *pEnd != '\0') pEnd++; tmp = 0; while(pStart < pEnd) { tmp = tmp * 10 + (*pStart - '0'); pStart++; } result += (tmp << shift); shift -= 8; if (*pEnd == '\0') break; pStart = pEnd + 1; pEnd++; } return result; }
2.整数をIPアドレスに変換
char *int2ipstr (const int ip, char *buf) { sprintf (buf, "%u.%u.%u.%u", (uchar) * ((char *) &ip + 0), (uchar) * ((char *) &ip + 1), (uchar) * ((char *) &ip + 2), (uchar) * ((char *) &ip + 3)); return buf; }
 
3.c言語はどのように16進0 xABCDABCDをipアドレス形式に変換することを実現します
#include <stdio.h>
int main(){
 unsigned int num=0xABCDABCD;    //         
 unsigned int mask = 0xff000000; // ip 8bitmask   1      
 int i;
 unsigned int val;
 
 for(i=0; i<4; i++){
  val = num & mask;  // mask    
  val = (val >> 8*(3-i) ); //            
  printf("%ud ", val);
  mask = mask >> 8;  // mask   8 
 }
 return 0;
}