qt 中 如何使用addrinfo
时间: 2024-06-09 17:12:00 浏览: 96
qt 实现ad采集
5星 · 资源好评率100%
在Qt中使用addrinfo可以通过以下步骤进行:
1. 引入头文件:
```c++
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
```
2. 定义addrinfo结构体及相关变量:
```c++
struct addrinfo hints, *res;
int status;
```
3. 初始化hints结构体:
```c++
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // 支持 IPv4 或 IPv6
hints.ai_socktype = SOCK_STREAM; // TCP协议
```
4. 调用getaddrinfo函数获取地址信息:
```c++
status = getaddrinfo("www.google.com", "http", &hints, &res);
if (status != 0) {
qDebug() << "getaddrinfo error: " << gai_strerror(status);
return;
}
```
5. 遍历res链表获取IP地址:
```c++
struct addrinfo *p;
char ipstr[INET6_ADDRSTRLEN];
for (p = res; p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
// 获取地址
if (p->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
// 将地址转换为字符串格式
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
qDebug() << ipver << ": " << ipstr;
}
```
6. 释放addrinfo结构体:
```c++
freeaddrinfo(res);
```
阅读全文