1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include<errno.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(void){
char buf [2048];
struct ifconf ic;
int i;
int sock;
struct ifreq *ifp;
struct sockaddr_in *s;
char if_name[32];
char if_addr[32];
/* Creation de notre socket permettant d'utiliser notre IOCTL */
if ((sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){
fprintf(stderr,"Erreur lors de la creation de la socket pour l'ioctl : %s\n",strerror(errno));
exit(EXIT_FAILURE);
}
/* On fournit un buffer vide afin de savoir de combien de place il aura besoin */
ic.ifc_len = 0;
ic.ifc_ifcu.ifcu_buf = (caddr_t)NULL;
getif_again:
i = ioctl(sock, SIOCGIFCONF, &ic);
if(i<0){
fprintf(stderr,"Erreur lors de l'appel a IOCTL : %s\n",strerror(errno));
exit(EXIT_FAILURE);
}
/* On verifie qu'il n'y a pas eu de bug */
if(ic.ifc_ifcu.ifcu_buf == 0 && ic.ifc_len == 0){
fprintf(stderr,"Bug trouve\n");
/* On passe par le buffer que l'on a cree */
ic.ifc_len = sizeof buf;
ic.ifc_ifcu.ifcu_buf = (caddr_t)buf;
goto getif_again;
}
/* On verifie que toutes les donnees ont pu tenir dans notre buffer
* Sinon on en alloue un plus grand
* Cf page de man de netdevice pour les conseils
* */
if ((ic.ifc_ifcu.ifcu_buf == buf || ic.ifc_ifcu.ifcu_buf == 0) && ic.ifc_len > sizeof buf){
if( (ic.ifc_ifcu.ifcu_buf = malloc ((size_t)ic.ifc_len)) == NULL ){
fprintf(stderr,"Erreur lors du malloc pour la definition du buffer : %s\n",strerror(errno));
exit(EXIT_FAILURE);
}
/* On refait notre IOCTL */
goto getif_again;
}else if(ic.ifc_ifcu.ifcu_buf == 0){
ic.ifc_ifcu.ifcu_buf = (caddr_t)buf;
ic.ifc_len = sizeof buf;
goto getif_again;
}
for(i=0;i<ic.ifc_len;){
/* Notre pointeur sur notre tableau d'elements ifreq */
ifp = (struct ifreq *)((caddr_t)ic.ifc_req + i);
/* On se deplace pour sauter au prochain element */
i += sizeof *ifp;
/* Notre pointeur sur notre structure de type sockaddr_in */
//interface = (struct sockaddr *) &ifp->ifr_addr;
/* On recupere les infos qui nous interessent */
/* Nom de l'interface */
strcpy(if_name,ifp->ifr_name);
/* Adresse de l'interface */
s = (struct sockaddr_in *) &(ifp->ifr_addr);
strcpy(if_addr,inet_ntoa(s->sin_addr));
fprintf(stdout,"Informations sur l'interface %s :\n\tAddresse : %s\n\n",if_name,if_addr);
}
return(EXIT_SUCCESS);
} |
Partager