ifaddr initial import

This commit is contained in:
Paul Schneider
2025-06-21 15:37:10 +01:00
commit 87e5e3337e
5 changed files with 91 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/build/

3
README.adoc Normal file
View File

@ -0,0 +1,3 @@
= Read me
This command outputs the ipv4 address for the interface given by name in argument.

9
src/Makefile Normal file
View File

@ -0,0 +1,9 @@
DESTDIR=../build
$(DESTDIR)/ifaddr: main.c getifaddr.c
mkdir -p $(DESTDIR)
gcc $^ -o $(DESTDIR)/ifaddr
dist-clean:
rm -f ifaddr $(DESTDIR)/ifaddr

53
src/getifaddr.c Normal file
View File

@ -0,0 +1,53 @@
#define _GNU_SOURCE /* To get defns of NI_MAXSERV and NI_MAXHOST */
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/if_link.h>
#include <string.h>
char * get_if_addr(char *ifname)
{
struct ifaddrs * list, * plist;
int family, s;
char host[NI_MAXHOST];
char *result;
if (getifaddrs (&list)==-1)
{
fprintf(stderr, "no info");
return NULL;
}
plist = list;
while (plist!=NULL)
{
if (strcmp(plist->ifa_name,ifname)==0)
{
family = plist->ifa_addr->sa_family;
if (family == AF_INET || family == AF_INET6) {
s = getnameinfo(plist->ifa_addr,
(family == AF_INET) ? sizeof(struct sockaddr_in) :
sizeof(struct sockaddr_in6),
host, NI_MAXHOST,
NULL, 0, NI_NUMERICHOST);
if (s != 0) {
fprintf(stderr, "getnameinfo() failed: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
result = malloc(strlen(host)+1);
strcpy(result,host);
freeifaddrs (list);
return result;
}
}
plist = plist->ifa_next;
}
freeifaddrs (list);
return NULL;
}

24
src/main.c Normal file
View File

@ -0,0 +1,24 @@
#include <stdio.h>
#include<stdlib.h>
char * get_if_addr(char *ifname);
int main(int argc, char ** argv)
{
if (argc<2) {
fprintf(stderr, "usage: %s <ifname>\nOù `ifname` est le nom de l'interface, par exemple, `eth0`.", argv[0]);
return 2;
}
char * addr = (char*) get_if_addr(argv[1]);
if (addr==NULL) {
printf("no addr found!\n");
return 1;
}
printf(addr);
free(addr);
return 0;
}