【问题标题】:How getservbyname can get the server port information if it is run on a client machine?如果 getservbyname 在客户端机器上运行,它如何获取服务器端口信息?
【发布时间】:2011-07-17 15:40:42
【问题描述】:

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

/*  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函数如何获取 参数列表中没有引用服务器机器的服务器信息?

【问题讨论】:

    标签: linux network-programming ubuntu-10.04


    【解决方案1】:

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

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

    【讨论】:

    • 这是我感到困惑的部分。假设我在命令行中为服务器机器名提供了一个主机名。这个客户端实际上并没有从提供的服务器机器上获取日期时间服务,而是从文件 /etc/services 获取本地信息。换句话说,我们假设服务器和客户端共享相同的服务信息。对吗?
    【解决方案2】:

    getservbyname 只需在/etc/services 中查找使用“tcp”协议的“白天”服务。

    这只是一种方便,让您免于解析该文件。

    编辑(澄清)

    这些协议中的每一个都有一个友好的名称(“daytime”、“http”等)和一个有用的名称(端口号 - 13、80 等)。 /etc/services 持有这个映射,仅此而已。

    【讨论】:

    • 你的意思是白天服务和服务器和客户端机器一样吗?
    • @q0987 我的意思是它只是一个标准端口号(和一个L4协议)。
    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 2012-03-27
    • 2012-10-31
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多