曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 3870|回复: 0
打印 上一主题 下一主题

gethostbyport() -- 根据端口号获取服务信息

[复制链接]

4917

主题

5879

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34382
跳转到指定楼层
楼主
发表于 2012-6-10 03:01:46 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
getservbyname() 函数类似,gethostbyport() 函数可以根据给定的端口号来获取相关的服务信息,函数声明如下:
[Plain Text] 纯文本查看 复制代码
#include <netdb.h>
struct servent *getservbyport(int port, const char *proto);

第 1 个参数是端口号。
第 2 个参数指定用的是哪种协议。

测试代码:
[C++] 纯文本查看 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>

int main(int argc, char **argv)
{
    struct servent *myserv;
    int port;

    if (argc < 3) {
              puts("Incorrect parameters. Use:");
             printf("%s service-port protocol-name", argv[0]);
              return EXIT_FAILURE;
    }


    port = htons(atoi(argv[1]));

    if (strcmp(argv[2], "NULL") == 0) {
        myserv = getservbyport(port, NULL);
        if (myserv == NULL) {
            printf("Port \"%s\" not found for protocol \"%s\"\n", argv[1], argv[2]);
            exit(EXIT_FAILURE);
        }
        printf ("Name: %-15s  Port: %5d    Protocol: %-6s\n", myserv->s_name, ntohs(myserv->s_port), myserv->s_proto);
    }
        
    else {
        myserv = getservbyport(port, argv[2]);
        if (myserv == NULL) {
            printf("Port \"%s\" not found for protocol \"%s\"\n", argv[1], argv[2]);
            exit(EXIT_FAILURE);
        }
        printf ("Name: %-15s  Port: %5d    Protocol: %-6s\n", myserv->s_name, ntohs(myserv->s_port), myserv->s_proto);
    }

    return 0;
}

运行输出:
# ./getservbyport 21 udp
Name: fsp              Port:    21    Protocol: udp  
# ./getservbyport 21 tcp
Name: ftp              Port:    21    Protocol: tcp  
# ./getservbyport 21 NULL
Name: ftp              Port:    21    Protocol: tcp  
# ./getservbyport 32 tcp
Port "32" not found for protocol "tcp"

函数如果找不到相应的“端口--服务” 匹配项时,返回 NULL 空指针。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-10 01:35 , Processed in 0.074563 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表