I would like to send ethernet packets in a loop and then receive the reply packet (if any). Here the short version of the code (hope its understandable enough):
Code:
for (int i=0; i<someValue; i++) {
// Submit request for a raw socket descriptor.
if ((sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) {
perror ("socket() failed ");
exit (EXIT_FAILURE);
}
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 1000;
if (setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
perror("Error");
}
char packet[1024];
int bytes;
// Send ethernet frame to socket.
if ((bytes = sendto (sock_fd, ether_frame, packet_length, 0, (struct sockaddr *) &device, sizeof (device))) <= 0) {
perror ("sendto() failed");
exit (EXIT_FAILURE);
} else {
if ((bytes = recv(sock_fd, packet, sizeof(packet), 0)) <= 0) {
printf("ERROR READ\n");
exit(1);
}
//Do something with the received packet...
}
}
When I omit the setting of the timeout setsocket(...) everything works fine so there must be something wrong with that but I can't figure out what??
P.S. Is there probably a better way to send those packets as the way I'm doing it?