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
*/