How to calculate arrival time of packet?

I would like to know, how I can calculate the arrival time of a packet sended from the client. I have try to send a timestamp (milliseconds since 1970) with the packet and then calculate it like this on the server.

timestamp_on_server - timestamp_from_packet

But the problem with this, is that I also get negative numbers and that isn't correct.

So how do I do this the right way? :-)

Thanks!

This does not work when machines are not properly synchronized to a time source (see NTP).

But in general, it's not the greatest idea to rely on the time sampled on different nodes. What you can do instead is measure the round-trip times (packet sent there and reflected back with sender's timestamp intact), so you only ever work with the same time source.

Side note: clock on the same machine can still jump back if forcefully adjusted by some privileged process, so it's probably a good idea to ignore (and maybe log) negative RTT values.