First, you only need to create one socket. So, start with
Code:
sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sock_fd == -1) {
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)) == -1)
perror("Warning: Cannot set socket receive timeout");
Then, you can do the loop.
Code:
for (int i=0; i<someValue; i++) {
ssize_t bytes;
// Send ethernet frame to socket.
bytes = sendto(sock_fd, ether_frame, packet_length, 0, (struct sockaddr *) &device, sizeof (device));
if (bytes != packet_length) {
if (bytes == (ssize_t)-1)
perror("sendto() failed");
else
fprintf(stderr, "sendto() only sent %d of %d bytes!\n", (int)bytes, (int)packet_length);
exit(EXIT_FAILURE);
}
bytes = recv(sock_fd, packet, sizeof packet, 0);
if (bytes == (ssize_t)-1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
fprintf(stderr, "No packet yet.\n");
continue;
}
if (bytes == (ssize_t)-1 && errno == EINTR) {
fprintf(stderr, "No packet yet; interrupted by a signal.\n");
continue;
}
if (bytes == (ssize_t)-1) {
perror("recv() failed");
exit(EXIT_FAILURE);
}
//Do something with the received packet...
}
Originally Posted by
Freaky256
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??
You get -1 and errno==EAGAIN (or errno==EWOULDBLOCK), because you have set a timeout of one millisecond, and it elapses before a packet arrives.
May I suggest you set a higher timeout than 1ms? 1000 µs = 1 ms = 0.000001 second. The valid range for .tv_usec is between 0 and 999999, i.e. zero and just under one million. (Don't exceed 999999, either; put full seconds in .tv_sec.)