比较C中包含IPv4地址的字符串

KAK*_*KAK 3 c ipv4

我有两个字符串ip1 = "192.168.145.123"ip2 = "172.167.234.120".

我可以比较这两个字符串是否相等:

strncmp(ip1,ip2) == 0
Run Code Online (Sandbox Code Playgroud)

但是我怎么能找到答案

if (ip1 > ip2) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

我试过了什么

我可以使用sscanf:

sscanf(ip1,"%d.%d.%d.%d",&s1,&s2,&s3,&s4) 
Run Code Online (Sandbox Code Playgroud)

并存储数字并进行比较.但是在32位中,由于上限,我无法将数字存储为整数.

因此,我别无选择,只能将整数作为字符串进行比较.

Geo*_*roy 14

是否值得一提的是,还有inet_aton?

您可以在这里找到手册页,下面是简短的描述和简短的概要.

这个解决方案适用于大多数POSIX系统,但我确信Windows API中有一些等价物,甚至还有一些抽象包装器.

inet_ntoa()在POSIX.1-2001中指定.ineix_aton()未在POSIX.1-2001中指定,但在大多数系统上都可用.


Linux程序员手册

inet_aton()将Internet主机地址cp从IPv4数字和点符号转换为二进制形式(按网络字节顺序),并将其存储在inp指向的结构中.

概要

#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);
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

节目来源

   #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);
   }
Run Code Online (Sandbox Code Playgroud)

进一步的信息

  • 字节订购(@Jonathan Leffler)

    inet_ntoa()函数in将以网络字节顺序给出的Internet主机地址转换为IPv4点分十进制表示法中的字符串. inet_aton() 将Internet主机地址 cp 从IPv4数字和点符号转换为二进制形式(按网络字节顺序),并将其存储在inp指向的结构中.

  • in_addr(@POW)的结构

    inet_ntoa(),inet_makeaddr(),inet_lnaof()和inet_netof()中使用的结构in_addr定义如下:

       typedef uint32_t in_addr_t;
    
       struct in_addr {
           in_addr_t s_addr;
       };
    
    Run Code Online (Sandbox Code Playgroud)
  • 独立于计算机字节顺序的地址比较地址in_addr是网络字节顺序(big-endian),所以@glglgl指出,你必须使用ntohl,其手册页在这里可用.

    ntohl()函数将无符号整数netlong从网络字节顺序转换为主机字节顺序.

    uint32_t ntohl(uint32_t netlong);
    
    Run Code Online (Sandbox Code Playgroud)