ioctl和struct ifreq
阿新 • • 發佈:2019-01-06
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string .h>
#include <net/if.h>
#include <net/netopt.h>
int main()
{
int i=0;
int sockfd;
struct ifconf ifconf;
unsigned char buf[512];
structifreq *ifreq;
//初始化ifconf
ifconf.ifc_len = 512;
ifconf.ifc_buf = buf;
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0)
{
perror("socket" );
exit(1);
}
ioctl(sockfd, SIOCGIFCONF, &ifconf); //獲取所有介面資訊
//接下來一個一個的獲取IP地址
ifreq = (struct ifreq*)buf;
for (i=(ifconf.ifc_len/sizeof (struct ifreq)); i>0; i--)
{
// if(ifreq->ifr_flags == AF_INET){ //for ipv4
printf("name = [%s]/n" , ifreq->ifr_name);
printf("local addr = [%s]/n" ,inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr));
ifreq++;
// }
}
return 0;
}
linux下怎樣取得網絡卡的硬體地址
#include <stdio.h>#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <arpa/inet.h>
#define inaddrr( x ) ( *( struct in_addr * )&ifr->x[ sizeof( sa.sin_port ) ] )
#define IFRSIZE ( ( int )( size * sizeof( struct ifreq ) ) )
int main ( void )
{
unsigned char * u;
int sockfd, size = 1;
struct ifreq * ifr;
struct ifconf ifc;
struct sockaddr_in sa;
if ( 0 > ( sockfd = socket( AF_INET, SOCK_DGRAM, IPPROTO_IP ) ) )
{
fprintf( stderr, "Cannot open socket.\n" );
exit( EXIT_FAILURE );
}
ifc.ifc_req = NULL;
do
{
++size;
/* realloc buffer size until no overflow occurs */
if ( NULL == ( ifc.ifc_req = realloc( ifc.ifc_req, IFRSIZE ) ) )
{
fprintf( stderr, "Out of memory.\n" );
exit( EXIT_FAILURE );
}
ifc.ifc_len = IFRSIZE;
if ( ioctl( sockfd, SIOCGIFCONF, &ifc ) )
{
perror( "ioctl SIOCFIFCONF" );
exit( EXIT_FAILURE );
}
} while ( IFRSIZE <= ifc.ifc_len );
ifr = ifc.ifc_req;
for ( ; ( char * )ifr < ( char * )ifc.ifc_req + ifc.ifc_len; ++ifr )
{
if ( ifr->ifr_addr.sa_data == ( ifr + 1 )->ifr_addr.sa_data )
{
continue; /* duplicate, skip it */
}
if ( ioctl( sockfd, SIOCGIFFLAGS, ifr ) )
{
continue; /* failed to get flags, skip it */
}
printf( "Interface: %s\n", ifr->ifr_name );
if ( 0 == ioctl( sockfd, SIOCGIFHWADDR, ifr ) )
{
switch ( ifr->ifr_hwaddr.sa_family )
{
case ARPHRD_NETROM:
case ARPHRD_ETHER:
case ARPHRD_PPP:
case ARPHRD_EETHER:
case ARPHRD_IEEE802:
break;
default:
printf( "\n" );
continue;
}
u = ( unsigned char * )&ifr->ifr_addr.sa_data;
if ( u[0] + u[1] + u[2] + u[3] + u[4] + u[5] )
{
printf( "HW Address: %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n",
u[0], u[1], u[2], u[3], u[4], u[5] );
}
}
printf( "\n" );
} /* end of for */
close( sockfd );
return( EXIT_SUCCESS );
}
參考: