Home > other >  Why after the success of the udp send, then recvfrom always don't get the message
Why after the success of the udp send, then recvfrom always don't get the message

Time:04-26

# include
# include
# include
# include
# include
# pragma comment (lib, "ws2_32. Lib")

# define NTP_VERSION 3
# define NTP_MODE_CLIENT 0 x3

# define NTP_HEADER_VERSION_SET (_header, _x) (_header |=((_x & 0 x7) <0))
# define NTP_HEADER_MODE_SET (_header, _x) (_header |=((_x & 0 x7) <3))

Typedef struct
{
Int seconds;
Int fraction;
} ntp_timestamp;

Typedef struct
{
Int the header;
Int root_delay;
Int root_dispersion;
Int reference_identifier;
Ntp_timestamp reference_timestamp;
Ntp_timestamp originate_timestamp;
Ntp_timestamp receive_timestamp;
Ntp_timestamp transmit_timestamp;
} ntp_rsp_msg;

Void print_words (size_t num_words, int buffer [])
{
Size_t word_i;

For (word_i=0; Word_i {
Printf (" % 2 lu: % # x \ n ", word_i, buffer [word_i]);
}
}

Int main (void)
{
Const int ntp_port=123;
Const char * ntp_host="210.72.145.44";
Int ntp_socket;
Int xit_addrlen=sizeof (struct sockaddr_in);
Struct sockaddr_in server;
Ntp_rsp_msg ntp_req_msg;
Int receive_len;
Ntp_rsp_msg ntp_rsp_msg;
Long seconds;
WSADATA data;
WORD version=MAKEWORD (2, 2);
WSAStartup (version, & data);
Ntp_socket=socket (AF_INET, SOCK_DGRAM, 0);

If (ntp_socket==1)
{
Perror (" Failed to create socket ");
return 0;
}

Memset (& server, 0, sizeof (server));
Server. The sin_family=AF_INET;
Server. The sin_port=htons (ntp_port);
Server. The sin_addr. S_addr=inet_addr (ntp_host);
If (server) sin_addr) s_addr==INADDR_NONE)
{
Fprintf (stderr, "Failed to resolve the hostname % s \ n", ntp_host);
return 0;
}

Memset (& ntp_req_msg, 0, sizeof (ntp_req_msg));
NTP_HEADER_VERSION_SET (ntp_req_msg. Header, NTP_VERSION);
NTP_HEADER_MODE_SET (ntp_req_msg. Header, NTP_MODE_CLIENT);
Printf (" Sending the NTP request to % s: % d \ n ", ntp_host, ntp_port);
If (sendto (ntp_socket,
(char *) & ntp_req_msg, sizeof (ntp_req_msg),
0,
(struct sockaddr *) & server, sizeof (struct sockaddr_in))==1)
{
Perror (" Failed to send the NTP request ");
return 0;
}

Printf (" Waiting for the response (NTP)... \n");
Receive_len=recvfrom (ntp_socket,
(char *) & ntp_rsp_msg, sizeof (ntp_rsp_msg),
0,
NULL,
0);
If (receive_len <=0)
{
Perror (" Failed to receive the response (NTP) ");
return 0;
}

Printf (" % d bytes Received \ n ", receive_len);
Print_words (receive_len/sizeof (int), (int *) & ntp_rsp_msg);

Seconds=ntohl (ntp_rsp_msg. Transmit_timestamp. Seconds);
Printf (" the Transmit seconds: % lu \ n ", and seconds).
Ntp_socket=1;

return 1;
}
  • Related