IP相关的一些代码
扫描二维码
随时随地手机看文章
#include2 #include3 4 #define IP_STR_LEN 18 5 #define MAC_STR_LEN 18 6 #define MAC_BIT_LEN 6 7 #define LITTLE_ENDIAN 0 8 #define BIG_ENDIAN 1 9 10 typedef unsigned char uchar; 11 typedef unsigned int uint; 12 13 int big_little_endian() 14 { 15 int data = 0x1; 16 if (*((char*)&data) == 0x1) 17 return LITTLE_ENDIAN; 18 return BIG_ENDIAN; 19 } 20 21 uint ipstr2int(const char * ipstr) 22 { 23 assert(ipstr); 24 uint a,b,c,d; 25 uint ip = 0; 26 sscanf(ipstr,"%u.%u.%u.%u",&a,&b,&c,&d); 27 a = (a << 24) ; 28 b = (b << 16) ; 29 c = (c << 8) ; 30 d = (d << 0) ; 31 ip = a | b | c | d; 32 return ip; 33 } 34 35 char *int2ipstr(const uint ip, char *ipstr, const uint ip_str_len) 36 { 37 assert(ipstr); 38 if (big_little_endian() == LITTLE_ENDIAN) 39 sprintf(ipstr,"%u.%u.%u.%u", 40 (uchar)*((char*)(&ip)+3), 41 (uchar)*((char*)(&ip)+2), 42 (uchar)*((char*)(&ip)+1), 43 (uchar)*((char*)(&ip)+0)); 44 else 45 sprintf(ipstr,"%u.%u.%u.%u", 46 (uchar)*((char*)(&ip)+0), 47 (uchar)*((char*)(&ip)+1), 48 (uchar)*((char*)(&ip)+2), 49 (uchar)*((char*)(&ip)+3)); 50 51 return ipstr; 52 } 53 55 char *mac2str(const unsigned char *mac,char *mac_str,const uint mac_str_len) 56 { 57 assert(mac_str); 58 sprintf(mac_str,"%02X-%02X-%02X-%02X-%02X-%02X", 59 mac[0],mac[1],mac[2], 60 mac[3],mac[4],mac[5]); 61 } 62 63 int main() 64 { 65 char ip_str[IP_STR_LEN] = {0}; 66 char mac_str[MAC_STR_LEN] = {0}; 67 unsigned char mac[MAC_BIT_LEN] = {0XEF,0XAD,0XF4,0X4F,0XAA,0X0F}; 68 const char *ipstr = "10.0.3.193"; 69 unsigned int ip; 70 int2ipstr(167773121,ip_str,IP_STR_LEN); 71 mac2str(mac,mac_str,MAC_STR_LEN); 72 ip = ipstr2int(ipstr); 73 printf("%sn",ip_str); 74 printf("%sn",mac_str); 75 printf("ip:%un",ip); 76 return 0; 77 }