Get packet timestamp via ioctl call in socket file descriptor

I am working on a system with embedded linux. I am trying to get the timestamp of a packet from the stream that I receive on the socket.

After creating the socket, I do the following:

if (fd != -1) { int enabled = 1; setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, &enabled, sizeof(enabled); } 

After that I bind the socket, the socket is of type SOCK_STREAM. I successfully receive data on a socket by calling the recv(fd, buf, size, 0) function recv(fd, buf, size, 0) . Now, to get the timestamp of the received data, I'm currently trying to do the following:

 ret = recv(fd, buf, size, 0); if (ret > 0) { struct timeval tv_ioctl; tv_ioctl.tv_sec = 0; tv_ioctl.tv_usec = 0; int error = ioctl(fd, SO_TIMESTAMP, &tv_ioctl); printf("%ld.%ld - error = %d", (long int)tv_ioctl.tv_sec, (long int)tv_ioctl.tv_usec, error); } 

The output of the printf statement is always the following:

0.0 error = -1

An error = -1 indicates an ioctl call failed. I checked the test with getsockopt to check if the SO_TIMESTAMP parameter is set, getsockopt returns 0 for the SO_TIMESTAMP parameter, so it seems to be set correctly. I lost a little here, how can I continue to research why the ioctl call seems unsuccessful?

+6
source share
1 answer

ioctl to get the most recent timestamp on a SIOCGSTAMP socket; SO_TIMESTAMP is a socket option, not ioctl. Your code should read:

 int error = ioctl(fd, SIOCGSTAMP, &tv_ioctl); ^^^^^^^^^^ 

An alternative method for obtaining timestamps is to change recv to recvmmsg and extract the timestamp from the supporting data. This is more efficient since it includes fewer system calls ( Read sockets and timestamps ); However, ioctl is simpler.

Please note that SIOCGSTAMP and SO_TIMESTAMP are mutually exclusive - if you intend to use SIOCGSTAMP, you must disable SO_TIMESTAMP (with enabled = 0 ). This is because SO_TIMESTAMP directs the kernel to make the timestamp accessible through auxiliary data recvmmsg , rather than through SIOCGSTAMP.

+4
source

All Articles