我有两个字符串 ip1 = "192.168.145.123"
和 ip2 = "172.167.234.120"
。
我可以比较这两个字符串是否相等:
strncmp(ip1,ip2) == 0
但是我怎样才能知道
if (ip1 > ip2) {
...
}
我尝试过的
我可以使用 sscanf:
sscanf(ip1,"%d.%d.%d.%d",&s1,&s2,&s3,&s4)
并存储数字并进行比较。 但是在 32 位中,由于上限,我无法将数字存储为整数。
因此我别无选择,只能将整数作为字符串进行比较。
最佳答案
值得一提的是还有 inet_aton 吗?
您可以找到手册页 here , 下面是一个简短的描述和一个简短的概要。
此解决方案适用于大多数 POSIX 系统,但我确信 Windows API 中有一些等效项,甚至一些抽象包装器。
inet_ntoa() is specified in POSIX.1-2001. inet_aton() is not specified in POSIX.1-2001, but is available on most systems.
Linux Programmer's Manual
inet_aton() converts the Internet host address cp from the IPv4 numbers-and-dots notation into binary form (in network byte order) and stores it in the structure that inp points to.
概要
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int inet_aton(const char *cp, struct in_addr *inp);
char *inet_ntoa(struct in_addr in);
示例
inet_aton() 和 inet_ntoa() 的使用示例如下所示。以下是一些示例运行:
$ ./a.out 226.000.000.037 # Last byte is in octal 226.0.0.31 $ ./a.out 0x7f.1 # First byte is in hex 127.0.0.1
程序源码
#define _BSD_SOURCE
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
struct in_addr addr;
if (argc != 2) {
fprintf(stderr, "%s <dotted-address>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (inet_aton(argv[1], &addr) == 0) {
fprintf(stderr, "Invalid address\n");
exit(EXIT_FAILURE);
}
printf("%s\n", inet_ntoa(addr));
exit(EXIT_SUCCESS);
}
更多信息
字节顺序(@Jonathan Leffler)
The inet_ntoa() function converts the Internet host address
in
, given in network byte order, to a string in IPv4 dotted-decimal notation.inet_aton()
converts the Internet host addresscp
from the IPv4 numbers-and-dots notation into binary form (in network byte order) and stores it in the structure thatinp
points to.in_addr
的结构 (@POW)The structure in_addr as used in inet_ntoa(), inet_makeaddr(), inet_lnaof() and inet_netof() is defined in as:
typedef uint32_t in_addr_t; struct in_addr { in_addr_t s_addr; };
与独立于计算机字节顺序的地址进行比较
in_addr
中的地址采用网络字节顺序(big-endian),因此正如@glglgl 所指出的,您必须使用ntohl
,其手册页可用 here .The
ntohl()
function converts the unsigned integernetlong
from network byte order to host byte order.uint32_t ntohl(uint32_t netlong);
关于在 C 中比较包含 IPv4 地址的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18307529/