ioctl request to get the HW address
hi heres my sample code
Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/ioctl.h>
int main (void)
{
int sockfd;
int io;
char buffer[1024];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
perror("socket");
exit(1);
}
io = ioctl(sockfd, SIOCGIFHWADDR, (char *)buffer);
if(io < 0){
perror("ioctl");
exit(1);
}
printf("fetched HW address with ioctl on sockfd.\n");
printf("HW address of interface is: %s\n", buffer);
exit(0);
}
why am i getting a "bad address" error with ioctl?
i found the constant used with the ioctl in bits/ioctls.h.
sockfd is obviously a socket but why isnt it working?
thanks
Correct way to get the eth0 hwaddr using ioctl
Hello,
I fixed your code. You will need to include the net/if.h and use the struct ifreq to pass the request info (fill in the eth0 for IF name first), and get the result in the same structure.
Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <net/if.h>
int main (void)
{
int sockfd;
int io;
char buffer[1024];
struct ifreq ifr;
sprintf(ifr.ifr_name, "eth0");
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
perror("socket");
exit(1);
}
io = ioctl(sockfd, SIOCGIFHWADDR, (char *)&ifr);
if(io < 0){
perror("ioctl");
exit(1);
}
printf("fetched HW address with ioctl on sockfd.\n");
printf("HW address of interface is: %02X:%02X:%02X:%02X:%02X:%02X\n",
(unsigned char)ifr.ifr_ifru.ifru_hwaddr.sa_data[0],
(unsigned char)ifr.ifr_ifru.ifru_hwaddr.sa_data[1],
(unsigned char)ifr.ifr_ifru.ifru_hwaddr.sa_data[2],
(unsigned char)ifr.ifr_ifru.ifru_hwaddr.sa_data[3],
(unsigned char)ifr.ifr_ifru.ifru_hwaddr.sa_data[4],
(unsigned char)ifr.ifr_ifru.ifru_hwaddr.sa_data[5]
);
exit(0);
}
TuomasKK