为了方便操作,linux提供了一组用于查询协议的值及名称的函数。
xxxprotoxxx()函数:
上面的函数对文件/etc/protocols中的记录进行操作,文件中记录了协议的名称、值和别名等值,与struct protoent的定义一致。
使用协议族函数的例子:
首先,使用setprotoent(1)打开文件/etc/protocols,然后使用函数getprotobyname()查询函数并显示出来,最后使用函数endprotoent()关闭文件/etc/protocols。
#include <netdb.h>#include <stdio.h>voiddisplay_protocol(struct protoent *pt){ int i = 0; if(pt) { printf("protocol name: %s", pt->p_name); if(pt->p_aliases) { printf("alias name:"); while(pt->p_aliases[i]) { printf("%s ", pt->p_aliases[i]); i++; } } printf(", value: %d/n", pt->p_proto); }}intmain(int argc, char **argv){ int i = 0; const char *const protocol_name[] = { "ip", "icmp", "tcp", "udp", NULL }; setprotoent(1); while(protocol_name[i] != NULL) { struct protoent *pt = getprotobyname((const char *)&protocol_name[i][0]); if(pt) { display_protocol(pt); } i++; } endprotoent(); return(0);}
运行结果:
新闻热点
疑难解答