strtok()
strtok()的用法:
-
pstr = strtok(str, ".");
-
while(pstr != NULL)
-
{
-
ip[i] = (unsigned char)atoi(pstr);
-
-
i++;
-
pstr = strtok(NULL, ".");
-
}
另外,我们还可以使用sscanf()来解析一些特定字符串,如mac和ip
sscanf()
sscanf()的举例:
1.
2str
-
#define MACSTR "%02x:%02x:%02x:%02x:%02x:%02x"
-
#define MAC2STR (a[0]&0xff), (a[1]&0xff), (a[2]&0xff), (a[3]&0xff), (a[4]&0xff), (a[5]&0xff)
-
ntohl(a);
-
#define IPSTR "%u.%u.%u.%u"
-
#define IP2STR(a) (a >> 24 &0xff), (a >> 16 &0xff), (a >> 8 &0xff), (a&0xff)
2.
str2
-
#define STR2MAC(str_mac, dest_mac) sscanf(str_mac, "%02x:%02x:%02x:%02x:%02x:%02x", dest_mac, dest_mac+1, dest_mac+2, dest_mac+3, dest_mac+4, dest_mac+5)
-
#define STR2IP(str_ip, dest_ip) sscanf(str_ip, "%u.%u.%u.%u", dest_ip, dest_ip+1, dest_ip+2, dest_ip+3)
这2种写法都是错误的,是踩内存的,(即使恰巧结果是对的,也仅仅是因为所踩到的内存无关要紧罢了)。不信试着这样写:
-
#define STR2MAC(str_mac, dest_mac) sscanf(str_mac, "%02x:%02x:%02x:%02x:%02x:%02x", dest_mac+5, dest_mac+4, dest_mac+3, dest_mac+2, dest_mac+1, dest_mac)
-
#define STR2IP(str_ip, dest_ip) sscanf(str_ip, "%u.%u.%u.%u", dest_ip+3, dest_ip+2, dest_ip+1, dest_ip)
就会发现结果错误。这是
因为sscanf()的format中,要求必须严格输入,而这里%02x和%u都要求是32bit的,但输入的dest_mac和dest_ip却是unsigned char*。所以正确的宏定义:
-
#define STR2MAC(str_mac, dest_mac)\
-
do{\
-
unsigned int tmp_mac[6];\
-
if(sscanf(str_mac, "%02x:%02x:%02x:%02x:%02x:%02x", tmp_mac, tmp_mac+1, tmp_mac+2, tmp_mac+3, tmp_mac+4, tmp_mac+5) == 6){\
-
dest_mac[0] = (unsigned char)tmp_mac[0];\
-
dest_mac[1] = (unsigned char)tmp_mac[1];\
-
dest_mac[2] = (unsigned char)tmp_mac[2];\
-
dest_mac[3] = (unsigned char)tmp_mac[3];\
-
dest_mac[4] = (unsigned char)tmp_mac[4];\
-
dest_mac[5] = (unsigned char)tmp_mac[5];\
-
}\
-
}while(0)
-
#define STR2IP(str_ip, dest_ip)\
-
do{\
-
unsigned int tmp_ip[4];\
-
if(sscanf(str_ip, "%u.%u.%u.%u", tmp_ip, tmp_ip+1, tmp_ip+2, tmp_ip+3) == 4){\
-
*dest_ip = (tmp_ip[0]<<24) + (tmp_ip[1]<<16) + (tmp_ip[2]<<8) + tmp_ip[3];
-
}\
-
}while(0)
阅读(4412) | 评论(0) | 转发(0) |