69 lines
1.7 KiB
C
69 lines
1.7 KiB
C
|
|
/*
|
||
|
|
* getifaddr.c — retourne l'adresse IPv4 d'une interface réseau par son nom
|
||
|
|
*
|
||
|
|
* Usage : ifaddr <interface>
|
||
|
|
* Exemple : ifaddr eth0
|
||
|
|
* ifaddr enp3s0
|
||
|
|
*
|
||
|
|
* Dépendances : POSIX, getifaddrs(3)
|
||
|
|
* Compile : gcc -o ifaddr getifaddr.c
|
||
|
|
*
|
||
|
|
* Paul Schneider — reconstitué depuis pazof/myovh-zone
|
||
|
|
*/
|
||
|
|
|
||
|
|
#include <stdio.h>
|
||
|
|
#include <stdlib.h>
|
||
|
|
#include <string.h>
|
||
|
|
#include <ifaddrs.h>
|
||
|
|
#include <netinet/in.h>
|
||
|
|
#include <arpa/inet.h>
|
||
|
|
#include <sys/socket.h>
|
||
|
|
|
||
|
|
int main(int argc, char *argv[])
|
||
|
|
{
|
||
|
|
if (argc != 2) {
|
||
|
|
fprintf(stderr, "Usage: %s <interface>\n", argv[0]);
|
||
|
|
return EXIT_FAILURE;
|
||
|
|
}
|
||
|
|
|
||
|
|
const char *ifname = argv[1];
|
||
|
|
struct ifaddrs *ifaddr_list = NULL;
|
||
|
|
|
||
|
|
if (getifaddrs(&ifaddr_list) == -1) {
|
||
|
|
perror("getifaddrs");
|
||
|
|
return EXIT_FAILURE;
|
||
|
|
}
|
||
|
|
|
||
|
|
int found = 0;
|
||
|
|
for (struct ifaddrs *ifa = ifaddr_list; ifa != NULL; ifa = ifa->ifa_next) {
|
||
|
|
/* On cherche uniquement IPv4 (AF_INET) */
|
||
|
|
if (ifa->ifa_addr == NULL)
|
||
|
|
continue;
|
||
|
|
if (ifa->ifa_addr->sa_family != AF_INET)
|
||
|
|
continue;
|
||
|
|
if (strcmp(ifa->ifa_name, ifname) != 0)
|
||
|
|
continue;
|
||
|
|
|
||
|
|
char buf[INET_ADDRSTRLEN];
|
||
|
|
struct sockaddr_in *sa = (struct sockaddr_in *)ifa->ifa_addr;
|
||
|
|
|
||
|
|
if (inet_ntop(AF_INET, &sa->sin_addr, buf, sizeof(buf)) == NULL) {
|
||
|
|
perror("inet_ntop");
|
||
|
|
freeifaddrs(ifaddr_list);
|
||
|
|
return EXIT_FAILURE;
|
||
|
|
}
|
||
|
|
|
||
|
|
printf("%s\n", buf);
|
||
|
|
found = 1;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
|
||
|
|
freeifaddrs(ifaddr_list);
|
||
|
|
|
||
|
|
if (!found) {
|
||
|
|
fprintf(stderr, "ifaddr: interface '%s' not found or has no IPv4 address\n", ifname);
|
||
|
|
return EXIT_FAILURE;
|
||
|
|
}
|
||
|
|
|
||
|
|
return EXIT_SUCCESS;
|
||
|
|
}
|