Prelevare e settare informazioni interfacce di rete

Autore: Fabio Di Matteo
Ultima revisione: 21/03/2008

Ecco delle pratiche funzioni get/set utili per prelevare e settare informazioni sulle interfacce di rete:

#include <stdio.h>
#include <errno.h>
#include <string.h> 
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h> 
 
 
int SetIP(const char* interface,const char * adress)
{
 int test_sock=0;
 struct sockaddr_in* addr=NULL;
 struct ifreq ifr;
 
 memset( &ifr, 0, sizeof( struct ifreq ) );
 addr= (struct sockaddr_in *)&(ifr.ifr_addr);
 memset(addr, 0, sizeof( struct sockaddr_in) );
 addr->sin_len=sizeof(struct sockaddr_in);
 addr->sin_family=AF_INET;
 addr->sin_addr.s_addr=inet_addr(adress);
 
 test_sock = socket( PF_INET, SOCK_DGRAM, 0 );
 if( test_sock == -1 )
 {
  diag_printf("Cannot obtain socket :%s\n",strerror(errno));
  return (-1);
 }
 
 strncpy( ifr.ifr_name,interface,IFNAMSIZ);
 if( ioctl( test_sock, SIOCSIFADDR, &ifr ) != 0 )
 {
  diag_printf("Cannot set IP address of interface '%s' to 
'%s':%s\n",interface,adress,strerror(errno));
  close(test_sock);
  return (-1);
 }
 else diag_printf("IP address of '%s' set to '%s'\n",interface,adress);
 close(test_sock);
 return(0);
}
 
 
 
int GetIP(const char* interface)
{
 int test_sock=0;
 struct sockaddr_in *addrp=NULL;
 struct ifreq ifr;
 
 test_sock = socket( PF_INET, SOCK_DGRAM, 0 );
 if( test_sock == -1 )
 {
  printf("Impossibile creare il socket :%s\n",strerror(errno));
  return (-1);
 }
 
 memset(&ifr,0,sizeof( struct ifreq ) );
 strncpy(ifr.ifr_name,interface,IFNAMSIZ);
 
 if( ioctl( test_sock, SIOCGIFADDR, &ifr ) == -1 )
 {
  printf("Impossibile ottenere indirizzo IP di '%s':%s\n",interface,strerror(errno));
  close(test_sock);
  return (-1);
 }
 close(test_sock);
 
 addrp = (struct sockaddr_in *)&(ifr.ifr_addr);
 printf("Indirizzo IP dell\' interfaccia '%s' e\' '%s'\n",interface,inet_ntoa(addrp->sin_addr));
 return(0);
}
 
 
int GetMAC(const char* interface){
	int fd;
 	struct ifreq ifr;
 
 	fd = socket(AF_INET, SOCK_DGRAM, 0);
 
 	ifr.ifr_addr.sa_family = AF_INET;
 	strncpy(ifr.ifr_name, interface, IFNAMSIZ-1);
 
 	ioctl(fd, SIOCGIFHWADDR, &ifr);
 
 	close(fd);
 
 	printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
         (unsigned char)ifr.ifr_hwaddr.sa_data[0],
         (unsigned char)ifr.ifr_hwaddr.sa_data[1],
         (unsigned char)ifr.ifr_hwaddr.sa_data[2],
         (unsigned char)ifr.ifr_hwaddr.sa_data[3],
         (unsigned char)ifr.ifr_hwaddr.sa_data[4],
         (unsigned char)ifr.ifr_hwaddr.sa_data[5]);
 
}
 
int main()
{
 	GetIP("eth0");
	GetMAC("eth0");
 
return 0;
}