如何处理inet_ntop()故障

How to handle inet_ntop() failure?

本文关键字:故障 ntop inet 处理 何处理      更新时间:2023-10-16

首先,我的代码示例:

cout << "bla1" << endl;
struct addrinfo hints, *info;
int status;
memset(&hints, 0, sizeof hints);
char ip4[INET_ADDRSTRLEN];
char ip6[INET6_ADDRSTRLEN];
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
cout << "bla2" << endl;
status = getaddrinfo(url.c_str(), NULL, &hints, &info);
cout << "bla3" << endl;
if(!inet_ntop(AF_INET, &((const sockaddr_in *)info->ai_addr)->sin_addr , ip4, INET_ADDRSTRLEN)) {
  return ERROR_PAR;
}
cout << "bla4" << endl;

url变量包含要解析的地址(我正在处理简单的客户端/服务器DNS解析程序)。如果可以解决,一切都很好,但是当url无法解决时,我的输出只有

bla1bla2bla3

上面的代码位于分叉子进程中,因此它不会停止整个脚本,而是返回父进程,但没有错误(我正在测试返回值,在这种情况下,它应该是error_PAR=1,因此应该显示错误消息)。

我使用这些函数的方式是否有问题,或者问题一定在其他地方?

EDIT:在执行任何其他函数之前检查getaddrinfo返回值是很重要的。所以问题解决了。

要正式回答这个问题,请查看手册:

成功后,inet_ntop()返回一个指向dst的非空指针。如果出现错误,则返回NULL,并设置errno以指示错误。

所以你会做一些类似的事情:

#include <arpa/inet.h>
#include <stdio.h>                                                                                                                                                                                                 
#include <string.h>
#include <errno.h>
int main(void) {
    char *ip = "127.0.0.1";
    uint32_t src;
    inet_pton(AF_INET, ip, &src);
    char dst[INET_ADDRSTRLEN];
    if (inet_ntop(AF_INET, &src, dst, INET_ADDRSTRLEN)) {
        printf("converted value = %s n", dst);   
        return 0;                                                                                                                                        
    } else {
        printf("inet_ntop conversion error: %sn", strerror(errno));
        return 1;
    }
}