Linux uses the TCP protocol to obtain server time
Here is a small program in UNIX network programming that establishes a TCP connection to the server and then reads the current time and date that is simply sent back by the server in an intuitive, readable format.
#include "unp.h" int main (int argc, char **argv) {INTSOCKFD, n;charrecvline[maxline + 1];struct sockaddr_inservaddr;if ( ARGC! = 2) err_quit ("Usage:a.out <IPaddress>"); if (SOCKFD = socket (af_inet, sock_stream, 0)) < 0) Err_sys ("Socke T error "); Bzero (&servaddr, sizeof (SERVADDR)); servaddr.sin_family = Af_inet;servaddr.sin_port = htons (13);/* Daytime server */if (Inet_pton (Af_inet, argv[1], &servaddr.sin_addr) <= 0) err_quit ("Inet_pton error for%s", argv[ 1]); if (Connect (SOCKFD, (SA *) &servaddr, sizeof (SERVADDR)) < 0) Err_sys ("Connect Error"), while (n = Read (SOCKFD, Recvline, MAXLINE)) > 0) {recvline[n] = 0;/* null terminate */if (fputs (recvline, stdout) = = EOF) Err_sys ("Fputs error") ;} if (n < 0) Err_sys ("read error"); exit (0);}
Then we run this program several times, each with a different IP address as the command line parameter.
First we test the time of the machine, you must first open the Linux daytime service, the method is as follows
sudo apt-get install Xinetdsudo vi/etc/xinetd.d/daytime find this line and then change Yes to no (disable = yes) (disable = no) sudo/etc/init.d/xinetd restart
Test this machine
[Email protected]:/home/jiang/unp_study/unpv13e/intro#./DAYTIMETCPCLI 127.0.0.1
The result is:
OCT 00:39:36 CST
To test the daytime of the server on the Internet, you first have to find a server that supports the return time with the TCP protocol. Tested some possible hosts, found some that could be returned, some timeouts or denied access.
The list of possible hosts is listed below, which is the one in the lower right corner of windows that synchronizes time.
This uses the DIG directive to parse the domain name
Dig time.windows.com +short
Time.microsoft.akadns.net.
64.4.10.33
Run the program to try to get the time
./DAYTIMETCPCLI 64.4.10.33
First time
Connect Error:connection timed out
Second time
Connect Error:connection refused
Change server
Dig Time.nist.gov./daytimetcpcli 128.138.141.172
Results
56953 14-10-23 16:46:39 0 0 0.0 UTC (NIST) *
You can see it intuitively, the local time is 4 o'clock in the afternoon.
Ubuntu uses the TCP protocol to get server time