gpt4 book ai didi

c - 为什么将整个 `hints` 变量设置为 0?

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

我正在阅读 Beej 的网络编程指南和 chapter 5.1 ,在 showip.c 程序中,我看到以下代码行: memset(&hints, 0, sizeof hints);

在 freenode 上的 ##c channel 上进行讨论后,我推断出 memset 调用的原因可能是将 hints.ai_flags 的值设置为 0(请注意程序运行良好,我删除了该行并将 hints.ai_flags 显式初始化为 0)。如果这是真的,为什么他需要将整个结构设置为 0

这是完整的来源:

/*
** showip.c -- show IP addresses for a host given on the command line
*/

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];

if (argc != 2) {
fprintf(stderr,"usage: showip hostname\n");
return 1;
}

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
hints.ai_socktype = SOCK_STREAM;

if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 2;
}

printf("IP addresses for %s:\n\n", argv[1]);

for(p = res;p != NULL; p = p->ai_next) {
void *addr;
char *ipver;

// get the pointer to the address itself,
// different fields in IPv4 and IPv6:
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";
}

// convert the IP to a string and print it:
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\n", ipver, ipstr);
}

freeaddrinfo(res); // free the linked list

return 0;
}

最佳答案

它是 getaddrinfo() 函数文档所必需的(您将 hints 变量作为参数传递)。来自 man getaddrinfo :

All the other fields in the structure pointed to by hints must contain either 0 or a NULL pointer, as appropriate.

关于c - 为什么将整个 `hints` 变量设置为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29718029/

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