1. getservbyname
服务(指HTTP/SSH/TELNET这类协议)也是依赖于名字来认知,将名字和端口号的映射关系保存在一个文件中,那么即使端口号发生变化,我们也能找到相应的映射关系。
getservbyname函数根据给定的名字查找相应的服务。
其关系保存在:
toney@sw2:/etc$ cat services
# Network services, Internet style
#
# Note that it is presently the policy of IANA to assign a single well-known
# port number for both TCP and UDP; hence, officially ports have two entries
# even if the protocol doesn't support UDP operations.
#
# Updated from http://www.iana.org/assignments/port-numbers and other
# sources like http://www.freebsd.org/cgi/cvsweb.cgi/src/etc/services .
# New ports will be added on request if they have been officially assigned
# by IANA and used in the real-world or are needed by a debian package.
# If you need a huge list of used numbers please install the nmap package.
tcpmux 1/tcp # TCP port service multiplexer
echo 7/tcp
echo 7/udp
discard 9/tcp sink null
discard 9/udp sink null
systat 11/tcp users
daytime 13/tcp
daytime 13/udp
函数定义:
函数使用:
#include<stdio.h>
#include<netdb.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<string.h>
int main(int argc, char * argv[])
{
char **list_p;
struct servent *serv_info = NULL;
serv_info = getservbyname("http","tcp");
//serv_info = getservbyname("ftp","tcp");
//serv_info = getservbyname("domain","udp");
if (serv_info != NULL)
{
printf("offical name:%s\n",serv_info->s_name);//打印 正式名
printf("port: %d\n",ntohs(serv_info->s_port)); // 打印端口
printf("protocol:%s\n",serv_info->s_proto); //打印协议
if(*(serv_info->s_aliases))
{
printf("alias:\n");
for(list_p = serv_info->s_aliases;*list_p != NULL;list_p++)
printf("\t%s\n",*list_p); //二重指针,打印多个别名
}
}
return;
}
函数结果:
toney@sw2:~/study/network$ gcc getservbyname.c
toney@sw2:~/study/network$ ./a.out
offical name:http
port: 80
protocol:tcp
alias:
www
toney@sw2:~/study/network$
2. getservbyport
用于根据端口号和可选协议查找相应服务。
函数定义:
函数使用:
#include<stdio.h>
#include<netdb.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<string.h>
int main(int argc, char * argv[])
{
char **list_p;
struct servent *serv_info = NULL;
serv_info = getservbyport(htons(80),"tcp");
//serv_info = getservbyport(htons(22),"tcp");
//serv_info = getservbyport(htons(21),"tcp");
//serv_info = getservbyport(htons(53),"udp");
if (serv_info != NULL)
{
printf("offical name:%s\n",serv_info->s_name);
printf("port: %d\n",ntohs(serv_info->s_port));
printf("protocol:%s\n",serv_info->s_proto);
if(*(serv_info->s_aliases))
{
printf("alias:\n");
for(list_p = serv_info->s_aliases;*list_p != NULL;list_p++)
printf("\t%s\n",*list_p);
}
}
return;
}
函数结果:
toney@sw2:~/study/network$ gcc getservbyport.c
toney@sw2:~/study/network$ ./a.out
offical name:http
port: 80
protocol:tcp
alias:
www
toney@sw2:~/study/network$