和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 空指针。 |