这个怎么样 :-
#include<stdio.h>
#include<conio.h>
unsigned int convIP(const char ip[]) {
unsigned char s1, s2, s3, s4;
if (sscanf(ip, "%hhu.%hhu.%hhu.%hhu", &s1, &s2, &s3, &s4) != 4)
return 0;
/* Create a 32 bit Integer using left shift & bitwise OR
MSB LSB
+-----8----+-----8------+-----8-----+----8-----+
| s1 | s2 | s3 | s4 |
+----------+------------+-----------+----------+
*/
return (s1 << 24) | (s2 << 16) | (s3 << 8) | (s4 << 0);
}
int ipComp(const char ip1[], const char ip2[]) {
unsigned int ip_addr1 = convIP(ip1);
unsigned int ip_addr2 = convIP(ip2);
return (ip_addr1 >= ip_addr2);
}
int main()
{
printf("%d\n",ipComp("192.168.145.123","172.167.234.120") ); //1
printf("%d\n", ipComp("10.0.0.1","192.168.1.1") ); //0
printf("%d\n",ipComp("192.168.145.123","192.168.145.123")); //1
}
编辑:根据 H2CO3 的建议:
您通常应该避免使用sscanf
,而是可以使用strtol()
,如下所示:
unsigned long ip2int(const char *ip)
{
const char *end = ip + strlen(ip);
unsigned long n = 0;
while (ip < end) {
n <<= 8;
n |= strtoul(ip, (char **)&ip, 10);
ip++;
}
return n;
}