55
66#include < stdio.h>
77#include < sys/types.h>
8- #include < sys/socket.h>
9- #include < arpa/inet.h>
10- #include < netdb.h>
8+ #ifdef _WIN32
9+ # include < WinSock2.h>
10+ # define close (X ) closesocket(X)
11+ #else
12+ # include < sys/socket.h>
13+ # include < arpa/inet.h>
14+ # include < netdb.h>
15+ # include < unistd.h>
16+ #endif
1117#include < time.h>
1218#include < string.h>
13- #include < unistd.h>
1419
1520NTPClient::NTPClient (std::string hostname, uint16_t port) : hostname_(hostname), port_(port)
1621{
22+ #ifdef _WIN32
23+ WSADATA wsaData = { 0 };
24+ (void )WSAStartup (MAKEWORD (2 , 2 ), &wsaData);
25+ #endif ;
1726}
1827
1928void NTPClient::build_connection ()
@@ -41,7 +50,14 @@ void NTPClient::build_connection()
4150 socket_client.sin_addr .s_addr = inet_addr (ntp_server_ip.c_str ());
4251}
4352
44- NTPClient::~NTPClient () { close (socket_fd); }
53+ NTPClient::~NTPClient ()
54+ {
55+ close_socket ();
56+
57+ #ifdef _WIN32
58+ WSACleanup ();
59+ #endif
60+ }
4561
4662uint64_t NTPClient::request_time ()
4763{
@@ -60,7 +76,11 @@ uint64_t NTPClient::request_time()
6076 packet.li_vn_mode = 0x1b ;
6177
6278 std::cout << " Sending request\n " ;
63- response = write (socket_fd, (char *)&packet, sizeof (NTPPacket));
79+ #ifdef _WIN32
80+ response = sendto (socket_fd, (char *)&packet, sizeof (NTPPacket), 0 , (struct sockaddr *)&socket_client, sizeof (socket_client));
81+ #else
82+ response = write (socket_fd, (char *)&packet, sizeof (NTPPacket));
83+ #endif
6484
6585 if (response < 0 )
6686 {
@@ -69,7 +89,11 @@ uint64_t NTPClient::request_time()
6989 }
7090
7191 std::cout << " Reading request\n " ;
92+ #ifdef _WIN32
93+ response = recv (socket_fd, (char *)&packet, sizeof (NTPPacket), 0 );
94+ #else
7295 response = read (socket_fd, (char *)&packet, sizeof (NTPPacket));
96+ #endif
7397
7498 if (response < 0 )
7599 {
0 commit comments