获取网络号、网络名——getnetent(),getnetbyaddr(),getnetbyname()

本文介绍getnetent函数及其相关函数的功能与用法,并通过一个简单的C语言程序演示如何使用这些函数来读取网络数据库。文章还展示了如何解析并打印struct netent结构体中的字段,包括网络名称、别名列表、地址类型及网络编号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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

/* Description of data base entry for a single network.  NOTE: here a
   poor assumption is made.  The network number is expected to fit
   into an unsigned long int variable.  */
struct netent
{
  char *n_name;			/* Official name of network.  */
  char **n_aliases;		/* Alias list.  */
  int n_addrtype;		/* Net address type.  */
  uint32_t n_net;		/* Network number.  */
};

注意:
(1) netent.n_net 是主机字节序,跟 hostent 有所不同

(2) 原理:ubuntu 下是读取 /etc/networks 文件(见man getnetent)

/**
 * getnetent()
 * OS: Ubuntu 11.04 Server
 */
#include <stdio.h>
#include <netdb.h>


static void printnet(struct netent *net);


int main()
{
	struct netent *net = NULL;
	
	setnetent(1);
	while( (net = getnetent()) != NULL )
	{
		printnet(net);
		printf("\n");
	}
	endnetent();
	return 0;
}
static void printnet(struct netent *net)
{
	char **p = NULL;
	
	printf("name of network: %s\n", net->n_name);
	
	for(p = net->n_aliases; *p; p++)
	{
		printf("alias: %s\n", *p);
	}
	
	if(net->n_addrtype == AF_INET)
	{
		printf("address type: AF_INET\n");
	}
	else
	{
		printf("adress type: not IPv4 address\n");
	}
	
	printf("network number: %x\n", net->n_net);
}
/*
output:
name of network: link-local
address type: AF_INET
network number: a9fe0000


/etc/networks:
# symbolic names for networks, see networks(5) for more information
link-local 169.254.0.0
*/




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值