Ricerca di un indirizzo IP da un nome di interfaccia
-
06-07-2019 - |
Domanda
Su un box Linux, i nomi delle interfacce comuni sembrano eth0, eth1, ecc. So come trovare almeno un indirizzo IP usando gethostbyname
o funzioni simili, ma non ne conosco nessuno modo di specificare quale interfaccia denominata desidero l'indirizzo IP. Potrei usare ifconfig e analizzare l'output, ma sborsare per queste informazioni sembra ... inelegante.
C'è un modo, per esempio, di enumerare tutte le interfacce e i loro indirizzi IP (e forse gli indirizzi MAC) in una raccolta? O almeno qualcosa del genere gethostbyinterface (" eth0 ")
?
Soluzione
// Originally from http://www.tlug.org.za/wiki/index.php/Obtaining_your_own_IP_address
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
/**
* getIPv4()
*
* This function takes a network identifier such as "eth0" or "eth0:0" and
* a pointer to a buffer of at least 16 bytes and then stores the IP of that
* device gets stored in that buffer.
*
* it return 0 on success or -1 on failure.
*
* Author: Jaco Kroon <jaco@kroon.co.za>
*/
int getIPv4(const char * dev, char * ipv4) {
struct ifreq ifc;
int res;
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0)
return -1;
strcpy(ifc.ifr_name, dev);
res = ioctl(sockfd, SIOCGIFADDR, &ifc);
close(sockfd);
if(res < 0)
return -1;
strcpy(ipv4, inet_ntoa(((struct sockaddr_in*)&ifc.ifr_addr)->sin_addr));
return 0;
}
int main() {
char ip[16];
if(getIPv4("eth0", ip) == 0)
printf("IPv4: %s\n", ip);
else
printf("No IP\n");
return 0;
}
Aggiorna : spostato il link morto in un commento (per i posteri) (grazie a @obayhan) e aggiunto l'evidenziazione della sintassi.
Altri suggerimenti
modifica: ho visto che non ti piace il bombardamento. Quindi puoi vedere come ifconfig fa il suo lavoro (estrae almeno alcune informazioni da / proc).
Quando hai il nome dell'interfaccia, puoi farlo (nella tua shell):
ifconfig eth0 | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
Per enumerare le interfacce puoi usare questo:
ifconfig | egrep '^[^ ]' | awk '{print $1}'
In combinazione:
for x in `ifconfig | egrep '^[^ ]' | awk '{print $1}'`; do
echo -n "${x}"
echo -n " "
ifconfig "${x}" | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
done