getservbyname函数和getservbyport函数其实也挺简单的。来看看百度百科是怎么描述他们的。getservbyname()返回与给定服务名对应的包含名字和服务号信息的servent结构指针;getservbyport()函数返回对应于给定端口号和协议名的相关服务信息,再来看看servent结构体。
struct servent {
char * s_name;
char * * s_aliases;
short s_port;
char * s_proto;
};
给出一段测试的小代码:
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
struct servent *sptr;
sptr=getservbyname("echo","udp");
printf("port=%d\n",ntohs(sptr->s_port));
sptr=getservbyname("ftp","tcp");
printf("port=%d\n",ntohs(sptr->s_port));
sptr=getservbyport(htons(7),"udp");
printf("name=%s\n",sptr->s_name);
sptr=getservbyport(htons(21),"tcp");
printf("name=%s\n",sptr->s_name);
return 0;
}
打印:
[mapan@localhost unixNetwork]$ ./a.out
port=7
port=21
name=echo
name=ftp
对下配置文件:
[mapan@localhost etc]$ cat services | grep echo
echo 7/tcp
echo 7/udp
ftp 21/tcp
ftp 21/udp
发现完全吻合。最后来玩一个gethostbyaddr的小程序。
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
char ip[]="127.0.0.1";
struct in_addr addr;
struct hostent *phost;
addr.s_addr=inet_addr(ip);
phost=gethostbyaddr(&addr,sizeof(addr),AF_INET);
if(phost == NULL)
{
printf("error\n");
}
printf("name=%s\n",phost->h_name);
return 0;
}
打印:
[mapan@localhost unixNetwork]$ ./a.out
name=localhost
无需多说。