📄 ethernet.c
字号:
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/ethernet.h>
#include <signal.h>
#include <netinet/ip.h>
struct in_addr myself,mymask;
int fd_arp;
struct ifreq ifr;
getmac(char *dev)
{
char device[32];
struct sockaddr from, to;
int fromlen;
struct sockaddr_in *sin_ptr;
u_char *ptr;
int n;
FILE *fp;
strcpy( device, dev );
if ( ( fd_arp = socket( AF_INET, SOCK_PACKET, htons( 0x0806 ) ) ) < 0 )
{
perror( "arp socket error" );
return;
}
strcpy( ifr.ifr_name, device );
if ( ioctl( fd_arp, SIOCGIFADDR, &ifr ) < 0 )
{
perror( "ioctl SIOCGIFADDR error" );
return;
}
sin_ptr = (struct sockaddr_in *)&ifr.ifr_addr;
myself = sin_ptr->sin_addr;
// get network mask
if ( ioctl( fd_arp, SIOCGIFNETMASK, &ifr ) < 0 )
{
perror( "ioctl SIOCGIFNETMASK error" );
return;
}
sin_ptr = (struct sockaddr_in *)&ifr.ifr_addr;
mymask = sin_ptr->sin_addr;
// get mac address
if ( ioctl( fd_arp, SIOCGIFHWADDR, &ifr ) < 0 )
{
perror( "ioctl SIOCGIFHWADDR error" );
return;
}
ptr=(u_char *)&ifr.ifr_ifru.ifru_hwaddr.sa_data[0];
printf("\nrequest mac %02x:%02x:%02x:%02x:%02x:%02x,",*ptr,*(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4),*(ptr+5));
printf("\nrequest netmask %s",inet_ntoa(mymask));
printf("\nrequest IP %s\n",inet_ntoa(myself));
/*if can find mac address, write it into the /usr/hostid file*/
if ( ( fp = fopen( "/usr/hostid", "w" ) ) == NULL )
{
printf( "Can not create the file!\n" );
return;
}
fprintf( fp, "hostid:%02x%02x%02x%02x%02x%02x1234",*ptr,*(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4),*(ptr+5) );
fclose( fp );
}
main()
{
char dev[56];
int i;
for (i=0; i<6; i++)
{
sprintf( dev, "eth%d", i );
getmac( dev );
}
printf( "File exists /usr/hostid\n" );
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -