|
|
@@ -23,8 +23,8 @@ static int sendNTPRequest(NTPClient* client) {
|
|
|
}
|
|
|
|
|
|
// 接收NTP响应
|
|
|
-static int receiveNTPResponse(NTPClient* client) {
|
|
|
- socklen_t len = sizeof(client->server_addr);
|
|
|
+static int receiveNTPResponse(NTPClient* client) {
|
|
|
+ socklen_t len = sizeof(client->server_addr);
|
|
|
ssize_t receivedBytes = recvfrom(client->sockfd, client->ntp_packet, NTP_PACKET_SIZE, 0,
|
|
|
&client->server_addr, &len);
|
|
|
if (receivedBytes < 0) {
|
|
|
@@ -81,9 +81,6 @@ static void *tmp_thread(void *arg)
|
|
|
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
|
|
|
pthread_testcancel();
|
|
|
|
|
|
- pc->res = NULL;
|
|
|
- pc->flag = 0;
|
|
|
-
|
|
|
sprintf(tmp, "%d", pc->port);
|
|
|
printf("___getaddrinfo in\n");
|
|
|
err = getaddrinfo(pc->server, tmp, &hints, &pc->res);
|
|
|
@@ -125,9 +122,11 @@ NTPClient* createNTPClient(const char* ntp_server, int port, int timeout_sec) {
|
|
|
pthread_t tid;
|
|
|
client->server = (char*)ntp_server;
|
|
|
client->port = port;
|
|
|
+ client->res = NULL;
|
|
|
+ client->flag = 0;
|
|
|
pthread_create(&tid, NULL, tmp_thread, client);
|
|
|
for(int i=0; i<timeout_sec; i++) {
|
|
|
- if(client->flag==1) {
|
|
|
+ if(client->flag) {
|
|
|
break;
|
|
|
}
|
|
|
sleep(1);
|
|
|
@@ -139,10 +138,16 @@ NTPClient* createNTPClient(const char* ntp_server, int port, int timeout_sec) {
|
|
|
pthread_join(tid, NULL);
|
|
|
printf("___cancel ok!\n");
|
|
|
}
|
|
|
- freeaddrinfo(client->res);
|
|
|
+ if(client->res) freeaddrinfo(client->res);
|
|
|
free(client); return NULL;
|
|
|
}
|
|
|
- freeaddrinfo(client->res);
|
|
|
+ if(client->res) freeaddrinfo(client->res);
|
|
|
+
|
|
|
+ struct timeval tv;
|
|
|
+ tv.tv_sec = timeout_sec;
|
|
|
+ tv.tv_usec = 0;
|
|
|
+ setsockopt(client->sockfd, SOL_SOCKET, SO_RCVTIMEO, (const void*)&tv, sizeof(tv));
|
|
|
+
|
|
|
printf("___createNTPClient ok!\n");
|
|
|
|
|
|
return client;
|