Linux下网络相关结构体 struct netent

来源:互联网 发布:程序员的简历怎么写 编辑:程序博客网 时间:2024/06/06 03:01

Linux下网络相关结构体 struct netent
参考书籍:《UNIX环境高级编程》
参考连接:
http://www.cnblogs.com/benxintuzi/p/4589819.htmlhttp://www.cnblogs.com/benxintuzi/p/4589819.html
http://www.qnx.com/developers/docs/6.5.0/index.jsp?topic=%2Fcom.qnx.doc.neutrino_lib_ref%2Fg%2Fgetnetbyname.html
http://www.yeolar.com/note/2012/05/18/linux-socket/

一.简介
strcuct netent 和struct hostent 的结构体有些类似。
结构体如下:

struct netent {    char      *n_name;         char     **n_aliases;      int        n_addrtype;uint32_t   n_net;   };

1.n_name
表示的是网络的规范名。
2.n_aliases
表示的是网络别名.
3.n_addrtype
表示的是ip地址的类型,到底是ipv4(AF_INET),还是pv6(AF_INET6)
4.n_net
IP地址,注意,这个是以网络字节序返回的。因此需要通过inet_ntoa(仅用于IPv4地址)或者inet_ntop(支持IPv4和IPv6)

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

struct netent *getnetent(void);void setnetent(int stayopen);void endnetent(void);struct netent *getnetbyname(const char *name);struct netent *getnetbyaddr(uint32_t net, int type);

2) getnetbyname
getnetbyname看似和前面的gethostbyname类似,并且struct netent和strcuct hostent结构类似,便以为getnetbyname也是通过域名获取IP地址,直接将上一篇blog中代码进行修改,然后输入“www.baidu.com”,但是返回值为NULL,百度也没有找到相应的解释,后来仔细阅读man手册后发现,该函数是将输入的网络名和“/etc/networks”配置文件里面的网络名进行匹配,成功返回strcut netent*结构。

1.代码

#include <stdio.h>#include <netdb.h>#include <sys/socket.h>#include <arpa/inet.h>int main(int argc, char **argv){char *ptr,**pptr;struct netent *hptr;char str[32];/* 取得命令后第一个参数,即要解析的域名或主机名 */ptr = argv[1];/* 调用getnetbyname()。调用结果都存在hptr中 */if( (hptr = getnetbyname(ptr) ) == NULL ){printf("getnetbyname error for host:%s\n", ptr);return 0; /* 如果调用gethostbyname发生错误,返回1 */}/* 将规范名打出来 */printf("official name:%s\n",hptr->n_name);/* 主机可能有多个别名,将所有别名分别打出来 */for(pptr = hptr->n_aliases; *pptr != NULL; pptr++)printf("  alias:%s\n",*pptr);printf("test\n");/* 根据地址类型,将地址打出来 */switch(hptr->n_addrtype){case AF_INET:case AF_INET6:/* 将刚才得到的所有地址都打出来。其中调用了inet_ntop()函数 */printf("net number: %u\n", hptr->n_net);//printf("address:%s\n", inet_ntop(hptr->n_addrtype, &hptr->n_net, str, sizeof(str)));break;default:printf("unknown address type\n");break;} return 0;}

2运行

$ cat /etc/networks# symbolic names for networks, see networks(5) for more informationlink-local 169.254.0.0$ ./test link-localofficial hostname:link-localtestnet number: 2851995648

3)getnetent
该函数直接读取“/etc/networks”,并返回一个netent structure
1.代码
参考下面的代码:

#include <stdio.h>#include <netdb.h>void printnet(struct netent* net){        char** p = net->n_aliases;        printf("net name: %s\n", net->n_name);        while(*p != NULL)        {                printf("alias name: %s\n", *p);                p++;        }        printf("address type: %d\n", net->n_addrtype);        printf("net number: %u\n", net->n_net);}int main(){        struct netent* net = NULL;        setnetent(1);        while((net = getnetent()) != NULL)        {                printnet(net);                printf("\n");        }        endnetent();        return 0;}

2.运行

$ ./testnet name: link-localaddress type: 2net number: 2851995648
原创粉丝点击