gpt4 book ai didi

linux - 如果在客户机上运行,​​getservbyname 如何获取服务器端口信息?

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

以下客户端程序尝试连接到服务器并查找该服务器上的当前时间和日期。

/*  Start with the usual includes and declarations.  */

#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
char *host;
int sockfd;
int len, result;
struct sockaddr_in address;
struct hostent *hostinfo;
struct servent *servinfo;
char buffer[128];

if(argc == 1)
host = "localhost";
else
host = argv[1];

/* Find the host address and report an error if none is found. */

hostinfo = gethostbyname(host);
if(!hostinfo) {
fprintf(stderr, "no host: %s\n", host);
exit(1);
}

/* Check that the daytime service exists on the host. */

servinfo = getservbyname("daytime", "tcp");
if(!servinfo) {
fprintf(stderr,"no daytime service\n");
exit(1);
}
printf("daytime port is %d\n", ntohs(servinfo -> s_port));

/* Create a socket. */

sockfd = socket(AF_INET, SOCK_STREAM, 0);

/* Construct the address for use with connect... */

address.sin_family = AF_INET;
address.sin_port = servinfo -> s_port;
address.sin_addr = *(struct in_addr *)*hostinfo -> h_addr_list;
len = sizeof(address);

/* ...then connect and get the information. */

result = connect(sockfd, (struct sockaddr *)&address, len);
if(result == -1) {
perror("oops: getdate");
exit(1);
}

result = read(sockfd, buffer, sizeof(buffer));
buffer[result] = '\0';
printf("read %d bytes: %s", result, buffer);

close(sockfd);
exit(0);
}

问题:

我们在客户端机器上运行上面的程序,函数getservbyname是如何得到在参数列表中没有引用服务器机器的服务器信息?

最佳答案

它检查 /etc/services 以查找具有给定服务名称和协议(protocol)的条目。

$ grep "^daytime\s.*/tcp" /etc/services 
daytime 13/tcp

关于linux - 如果在客户机上运行,​​getservbyname 如何获取服务器端口信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6724910/

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