Linux下网络相关结构体 struct protoent

来源:互联网 发布:贝叶斯算法 spark 编辑:程序博客网 时间:2024/06/05 04:53

参考书籍:《UNIX环境高级编程》
参考连接:
http://www.cnblogs.com/benxintuzi/p/4589819.html

一、简介
sutuct protoent主要用于提供协议名字和协议号
结构体如下:

struct protoent {    char  *p_name;        char **p_aliases;    int    p_proto;};

1.p_name
表示的是协议规范名。

2.h_aliases
表示的是主机的别名

3.p_proto
协议号

二、代码展示
1)相关函数

struct protoent *getprotoent(void);void setprotoent(int stayopen);void endprotoent(void);struct protoent *getprotobyname(const char *name);struct protoent *getprotobynumber(int proto);

2)getprotobyname
根据协议名字然后匹配“/etc/protocols”,匹配成功,返回struct protoent指针,失败返回空
1.代码

#include <netdb.h>#include <stdio.h>int main(){    struct protoent* proto = NULL;proto = getprotobyname("udp");if (proto != NULL){printf("proto name: %s\n", proto->p_name);printf("alias name: %s\n", *proto->p_aliases);printf("proto number: %d\n", proto->p_proto);}return 0;}

2.运行

$ ./testproto name: udpalias name: UDPproto number: 17

3)参考如下代码,读取“/etc/protocols”全部信息,并将其打印出来

#include <netdb.h>#include <stdio.h>void printproto(struct protoent* proto){        char** p = proto->p_aliases;        printf("proto name: %s\n", proto->p_name);        while(*p != NULL)        {                printf("alias name: %s\n", *p);                p++;        }        printf("proto number: %d\n", proto->p_proto);}int main(){        struct protoent* proto = NULL;        setprotoent(1);        while((proto = getprotoent()) != NULL)        {                printproto(proto);                printf("\n");        }        endprotoent();        return 0;}

2.运行

$ ./testproto name: ipalias name: IPproto number: 0proto name: hopoptalias name: HOPOPTproto number: 0proto name: icmpalias name: ICMPproto number: 1proto name: igmpalias name: IGMPproto number: 2proto name: ggpalias name: GGPproto number: 3proto name: ipencapalias name: IP-ENCAPproto number: 4proto name: stalias name: STproto number: 5proto name: tcpalias name: TCPproto number: 6proto name: egpalias name: EGPproto number: 8proto name: igpalias name: IGPproto number: 9proto name: pupalias name: PUPproto number: 12proto name: udpalias name: UDPproto number: 17......
原创粉丝点击