如何处理inet_ntop()故障
How to handle inet_ntop() failure?
首先,我的代码示例:
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;
}
}
相关文章:
- 分段故障(堆芯转储)矢量
- C++中的动态铸造故障
- 数组的指针从不分段故障
- vscode g++链路故障:体系结构x86_64的未定义符号
- 访问被拒绝后,c++中的故障保护代码
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 调试 CUDA MMU 故障
- Geeksforgeeks C 程序故障排除:IEE 754 表示法为十进制
- Arch Linux.AUR 包 mysql 不能用 makepkg 构建.错误:构建 () 中出现故障
- 正在处理故障(堆芯转储)
- 在 Boost::fiber 中引发的BOOST_ASSERT故障 Visual Studio "Debug" 构建
- 如何进行故障排除:未定义对"非虚拟 thunk to ..."的引用
- C++函数过载会导致 SEG 故障
- 分段故障 运行C++代码时出现 SIGSEGV
- 当新的故障时,是否有必要留出一些紧急内存?
- Python & C-C++ 扩展模块案例段故障
- 带升压的 SEG 故障::make_shared / 特征3 内存.h.
- 在 c++ 中,发生故障后是否需要 stream.clear()?
- 分段故障背包问题
- 分段故障 11,从类函数显示动态 C 字符串