Getservent() 未从 _PATH_SERVICES 读取

Getservent() is not reading from _PATH_SERVICES

我必须使用 getservbyname() 函数获取有关服务的信息,我检查过 _PATH_SERVICES 指的是服务数据库文件的“/etc/services”,但是当我尝试打印时返回infos 端口号是另一个。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>

void foo(){
//netdb.h is in /usr/include
//CHECK: is not reading from /etc/services
FILE * f;
f = fopen("/etc/services", "r");
char buffer[50000];
int index = 0;
//just try
while(index < 1000){
    buffer[index++] = fgetc(f);
}
printf("%s", buffer); //printed buffer corresponds to /etc/services contents
struct servent * serv;
serv = getservbyname("ftp", "tcp");
printf("Service name: %s\n", serv->s_name);
printf("Service port: %u\n", serv->s_port); //it would be 21, instead is 5376
printf("Service protocol: %s\n", serv->s_proto);
}


int main(void){
printf("Reading services from: %s\n", _PATH_SERVICES); //it returns "/etc/services"
foo();
return 0;
}

getservbyname()用的是getservent(),getservent()是从_PATH_SERVICES路径读取的,难不成不是从_PATH_SERVICES读取的?

谢谢大家!

您需要使用 ntohs(serv->s_port) 函数调用将网络字节顺序转换为主机字节顺序。

printf("Service port: %u\n", ntohs(serv->s_port));