Brain Dump

Network Interface

Tags
networking comp-arch
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>

int required_family = AF_INET; // Equivalently AF_INET6 is for IPv6
int family_size = (required_family == AF_INET)
    ? sizeof(struct sockaddr_in)
    : sizeof(struct sockaddr_in6);

struct ifaddrs *myaddrs;
getifaddrs(&myaddrs);
char host[256], port[256];

struct ifaddrs *ifa;
for (ifa = myaddrs; ifa != NULL; ifa = ifa->next) {
    // When the address exists and matches the protocol family we're interested in.
    if (ifa->ifa_addr && ifa->ifa_addr->sa_family == required_family) {
	int ret = getnameinfo(ifa->ifaaddr, family_size,
			      host, sizeof(host), port, sizeof(port),
			      NI_NUMERICHOST, NI_NUMERICSERV);
	if (ret == 0) {
	    puts(host);
	}
    }
}
Code Snippet 1: An example program retrieving all network interfaces and then printing the IP address of all of them with IPv4 configurations.