我很难理解以前的作业。我要使用 Addison-Wesley UNIX 环境中的高级编程 第三版文本(第 16.3.3 章)中给出的函数将主机、网络、协议(protocol)和服务数据库打印到标准输出。我的教授给出的反馈如下。
需要认真的工作(-40);输出的每个部分需要包含(可能)许多条目,并且必须循环读取服务端口号不正确(-5);端口是短的(不是 int 并且是网络字节顺序!);它必须使用 ntohs(3) 进行转换。
我的问题是循环程序以获取多个条目,因为我不确定如何做到这一点,尤其是 h_addr_list 中的地址,因为我遇到段错误试图访问 [0] 之后的任何内容。循环与h_length的值有什么关系吗?
这是为上述反馈提交的代码:
/*
* Dawson Binder
* Assignment 10 - assign10.c
* displays the host, network, protocol, and services databases.
*/
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
char address[36];
struct hostent *hPtr = gethostent(); // print host name, address type, address length, and the addresses
struct netent *nPtr = getnetent();
struct protoent *pPtr = getprotoent();
struct servent *sPtr = getservent();
// Host
printf("\nHost Name: %s\nAddress Type: %d\nAddress Length: %d\n", hPtr->h_name, hPtr->h_addrtype, hPtr->h_length);
inet_ntop(AF_INET, hPtr->h_addr_list[0], address, 36);
printf("Address: %s\n", address);
// end Host
// Network
printf("Network Name: %s\nNetwork Number: %u\n", nPtr->n_name, nPtr->n_net);
// end Network
//Protocol
printf("Protocol Name: %s\nProtocol Number: %d\n", pPtr->p_name, pPtr->p_proto);
//end Protocol
//Service Database
printf("Service Database Name: %s\nService Database Port: %d\nServiceDatabase Protocol: %s\n\n", sPtr->s_name, sPtr->s_port, sPtr->s_proto);
//end Service Database
return 0;
}
最佳答案
每次调用这四个 get*ent()
函数时,它们都会返回其数据库的一个条目,直到返回 NULL
。阅读他们的联机帮助页以了解更多信息,例如getservent(3)
.您可能还想关闭与它们的 end*net()
副本的数据库连接。
另请参阅相关问题,例如 How to loop getprotent() function .
关于c - 循环获取主机、网络、协议(protocol)和服务数据库中的多个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49517207/