Click here to Skip to main content
15,899,754 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,

I have written a SNTP Client code to retrieve time information as below. In this, the code stops at line _sntpMessageRequest.SNTPData = _udpClient.Receive(ref _ipEndpoint); as SNTP Server is not responding.
C#
public bool QueryTimeSynchronizationServer()
{
	UdpClient _udpClient = null;
	IPEndPoint _ipEndpoint = null;
	string _ipString = null;
	IPAddress _ipAddress = null;
	int _portNumber = 123;

	try
	{
		_ipString = "ip address";
		IPAddress.TryParse(_ipString, out _ipAddress);
		_ipEndpoint = new IPEndPoint(_ipAddress, _portNumber);

		 //SNTPMessageRequest-> a object holds the Byte array for SNTP request and do other supporting functions
		SNTPMessageRequest _sntpMessageRequest = FrameSNTPMessageRequest();

		using (_udpClient = new UdpClient(123))
		{
			_udpClient.Client.SendTimeout = 5000;
			_udpClient.Client.ReceiveTimeout = 5000;
			_udpClient.Connect(_ipEndpoint);

			_udpClient.Send(_sntpMessageRequest.SNTPData, _sntpMessageRequest.SNTPData.Length);

			 //Code stops at below line as SNTP Server is not responding.
			_sntpMessageRequest.SNTPData = _udpClient.Receive(ref _ipEndpoint);
			_sntpMessageRequest.ReceptionTimestamp = DateTime.Now;

			string _serverTime = _sntpMessageRequest.TransmitTimeStamp.ToString();
		}
	}
	catch (Exception ex)
	{
		
	}
	return true;
}

private SNTPMessageRequest FrameSNTPMessageRequest()
{
	 
	SNTPMessageRequest _sntpMessageRequest = new SNTPMessageRequest();

	_sntpMessageRequest.VersionNumber = VersionNumber.Version3;
	_sntpMessageRequest.Mode = Mode.Client;

	for (int i = 1; i < 48; i++)
	{
		_sntpMessageRequest.SNTPData[i] = 0;
	}

	_sntpMessageRequest.TransmitTimeStamp = DateTime.Now.ToLocalTime();
	return _sntpMessageRequest;
}

Kindly help me with where i am doing mistake.
Thanks in Advance.
Ranjith.

What I have tried:

I have tried sending SNTP request with all four versions(1-4), but the server is not responding.
Posted
Updated 5-Sep-17 2:07am
v2

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900