linux 中获取ip地址

Linux 中使用C语言实现的获取IP地址的接口

get_ifaddr.h

#ifndef GET_IP_H
#define	GET_IP_H
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#ifdef	__cplusplus
extern "C" {
#endif

int get_ifaddr();


#ifdef	__cplusplus
}
#endif

#endif	

get_ifaddr.c

#include "get_eth0_addr.h"
int get_ifaddr()
{
	struct ifaddrs *ifaddr, *ifa;
	int family, s;
	char host[NI_MAXHOST];

	if (getifaddrs(&ifaddr) == -1) {
		perror("getifaddrs");
		return -1;
	}

	/* Walk through linked list, maintaining head pointer so we
	*              can free list later */

	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr == NULL)
			continue;

		family = ifa->ifa_addr->sa_family;

		/* Display interface name and family (including symbolic
		*                  form of the latter for the common families) */

		printf("%s  address family: %d%sn",
				ifa->ifa_name, family,
				(family == AF_PACKET) ? " (AF_PACKET)" :
				(family == AF_INET) ?  " (AF_INET)" :
				(family == AF_INET6) ?  " (AF_INET6)" : "");

		/* For an AF_INET* interface address, display the address */

		if (family == AF_INET || family == AF_INET6) {
			s = getnameinfo(ifa->ifa_addr,
					(family == AF_INET) ? sizeof(struct sockaddr_in) :
					sizeof(struct sockaddr_in6),
					host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
			if (s != 0) {
				printf("getnameinfo() failed: %sn", gai_strerror(s));
				return -1;
			}
			printf("taddress: <%s>n", host);				
		}			
	}

	freeifaddrs(ifaddr);
	return 0;
}