Question: Using NTP _ Client.c and LocalTime _ Client.c examples, create a single program that obtains the current time from NTP and from the local computer.

Using NTP_Client.c and LocalTime_Client.c examples, create a single program that obtains the current time from NTP and from the local computer. Print both times and print the difference between the two times. On most systems, this should be a very small number as most systems sync their time via NTP. However, the exercise will give you an appreciation of how much local time can slip in between time
synchronization with an external clock.
NTP_client.c
#include
#include
#include
#include
#include
#include
#include
#include
#define NTP_SERVER "pool.ntp.org"
#define NTP_PORT 123
#define NTP_PACKET_SIZE 48
#define NTP_TIMESTAMP_DELTA 2208988800ull
typedef struct {
uint8_t li_vn_mode;
uint8_t stratum;
uint8_t poll;
uint8_t precision;
uint32_t root_delay;
uint32_t root_dispersion;
uint32_t reference_id;
uint32_t ref_ts_sec;
uint32_t ref_ts_frac;
uint32_t orig_ts_sec;
uint32_t orig_ts_frac;
uint32_t recv_ts_sec;
uint32_t recv_ts_frac;
uint32_t trans_ts_sec;
uint32_t trans_ts_frac;
} ntp_packet;
void error(const char *msg){
perror(msg);
exit(EXIT_FAILURE);
}
int main(){
int sockfd, n;
struct sockaddr_in serv_addr;
ntp_packet packet;
sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockfd <0)
error("ERROR opening socket");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(NTP_PORT);
if (inet_pton(AF_INET, NTP_SERVER, &serv_addr.sin_addr)<=0)
error("ERROR invalid address");
memset(&packet, 0, sizeof(packet));
packet.li_vn_mode =(0x03<<6)|(0x03<<3)|0x03;
if (sendto(sockfd, &packet, sizeof(packet),0,(struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
error("ERROR sending packet");
n = recv(sockfd, &packet, sizeof(packet),0);
if (n <0)
error("ERROR receiving response");
close(sockfd);
time_t current_time =(ntohl(packet.trans_ts_sec)- NTP_TIMESTAMP_DELTA);
printf("NTP time: %s", ctime(t_time));
return 0;
}
LocalTime_Client.C
#include
#include
int main(){
time_t current_time;
struct tm *local_time;
// Get current time
current_time = time(NULL);
// Convert to local time
local_time = localtime(t_time);
// Print local time
printf("Local time: %s", asctime(local_time));
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!