getservent

   getservent   

servent 结构体的成员:

struct servent
{
  char *s_name;            /* Official service name.  */
  char **s_aliases;        /* Alias list.  */        服务程序可选名字,空指针标志该数组结束                 
  int  s_port;             /* Port number.  */
  char *s_proto;           /* Protocol to use.  */   与该服务一起使用的协议名
};


相关函数:

/* Open service data base files and mark them as staying open even
   after a later search if STAY_OPEN is non-zero.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern void setservent (int __stay_open);

/* Close service data base files and clear `stay open' flag.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern void endservent (void);

/* Get next entry from service data base file.  Open data base if
   necessary.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern struct servent *getservent (void);

/* Return entry from network data base for network with NAME and
   protocol PROTO.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern struct servent *getservbyname (__const char *__name,
                      __const char *__proto);

/* Return entry from service data base which matches port PORT and
   protocol PROTO.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern struct servent *getservbyport (int __port, __const char *__proto);

 

样例程序:

 1 #include <stdio.h>
 2 #include <sys/socket.h>
 3 #include <netdb.h>
 4 
 5 /* 扫描主机的服务数据库,并打印出所有服务的信息 */
 6 
 7 int main()
 8 {
 9     int stayopen = 1;
10     struct servent *sp = 0;
11 
12     /* 打开服务器数据库,准备开始扫描 */
13     setservent(stayopen);
14 
15     /* 逐项扫描登记的项 */
16     while(1)
17     {
18         sp = getservent();
19         if( sp != (struct servent *)0 )
20         {
21             printf("sp->s_name = %s\n", sp->s_name);
22             printf("sp->s_port = %d\n", sp->s_port);
23             printf("sp->s_proto = %s\n\n", sp->s_proto);
24         }
25         else
26             break;
27     }
28 
29     /* 关闭服务器数据库 */
30     endservent();
31 
32     /* 通过名字来查询 telnet 的端口 */
33     sp = getservbyname("telnet", "tcp");
34     if( sp != (struct servent *)0 )
35         printf("telent's port is %d\n", ntohs(sp->s_port));
36     else
37         printf("Error: call "getservbyname" faild ...\n");
38 
39     /* 通过端口号来查询占用 23 号端口的服务器名字 */
40     sp = getservbyport(ntohs(23), "tcp");
41     if( sp != (struct servent *)0 )
42         printf("port 23 is %s\n", sp->s_name);
43     else
44         printf("Error: call "getservbyport" faild ...\n");
45 
46     return 0;
47 }

 

运行截图:

 

posted @ 2012-06-02 23:36  hp+y  Views(478)  Comments(0)    收藏  举报