gpt4 book ai didi

c - 如何从 sockaddr 获取 IP 地址

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:34 24 4
gpt4 key购买 nike

大家好
我试图从我的 res 结构中获取 IP 地址,但我仍然无法通过它,有人知道如何获取它们吗?

int main(int argc, char **argv) {
struct addrinfo hints, *res;

memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;

if(getaddrinfo(NULL, "50000", &hints, &res) != 0) {
perror("Error in getaddrinfo\n");
exit(-1);
}

//Print out the IPs from res

return 0;
}

最佳答案

IP 地址存储在 ai_addr 字段中。您可以使用 inet_ntop 获取 ip 地址,如下所示:

#include <stdio.h>
#include <arpa/inet.h>
#include <netdb.h>

void print_ips(struct addrinfo *lst) {
/* IPv4 */
char ipv4[INET_ADDRSTRLEN];
struct sockaddr_in *addr4;

/* IPv6 */
char ipv6[INET6_ADDRSTRLEN];
struct sockaddr_in6 *addr6;

for (; lst != NULL; lst = lst->ai_next) {
if (lst->ai_addr->sa_family == AF_INET) {
addr4 = (struct sockaddr_in *) lst->ai_addr;
inet_ntop(AF_INET, &addr4->sin_addr, ipv4, INET_ADDRSTRLEN);
printf("IP: %s\n", ipv4);
}
else if (lst->ai_addr->sa_family == AF_INET6) {
addr6 = (struct sockaddr_in6 *) lst->ai_addr;
inet_ntop(AF_INET6, &addr6->sin6_addr, ipv6, INET6_ADDRSTRLEN);
printf("IP: %s\n", ipv6);
}
}
}

关于c - 如何从 sockaddr 获取 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19817425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com