Category Archives: C++

Get the NTP time in a C++ programm via a simple socket

If you are writing an application it sometimes my be useful to have the exact time. Usually the time of the operating system is not synchronized. However, there is a very old protocol which available which allows servers so synchronize themselves: The Network Timing Protocol (NTP). It uses UDP port 123 for its communication. There is a huge network of free NTP time servers available in the web. The following example program connects to such a timing server and retrieves the NTP time from that server. For that it opens a simple socket connection in C++. The program can be compiled executed as it is here without any changes and also calculates the difference between the NTP time to your current system time. Furthermore you also learn how to use sockets in C++. We create a simple massage here, sent it via a socket to the NTP timing server and then receive the reply which is the desired time.

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
#include <string.h>
#include <iostream>
void ntpdate();

int main() {

 ntpdate();
 return 0;
}

void ntpdate() {
// can be any timing server
// you might have to change the IP if the server is no longer available
char *hostname=(char *)"200.20.186.76";
// ntp uses port 123
int portno=123;
int maxlen=1024;
int i;
// buffer for the socket request
unsigned char msg[48]={010,0,0,0,0,0,0,0,0};
// buffer for the reply
unsigned long buf[maxlen];
//struct in_addr ipaddr;
struct protoent *proto; //
struct sockaddr_in server_addr;
int s; // socket
long tmit; // the time -- This is a time_t sort of

// open a UDP socket
proto=getprotobyname("udp");
s=socket(PF_INET, SOCK_DGRAM, proto->p_proto);

//here you can convert hostname to ipaddress if needed
//$ipaddr = inet_aton($HOSTNAME);

memset( &server_addr, 0, sizeof( server_addr ));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr = inet_addr(hostname);
server_addr.sin_port=htons(portno);

/*
 * build a message. Our message is all zeros except for a one in the
 * protocol version field
 * msg[] in binary is 00 001 000 00000000
 * it should be a total of 48 bytes long
*/

// send the data to the timing server
i=sendto(s,msg,sizeof(msg),0,(struct sockaddr *)&server_addr,sizeof(server_addr));
// get the data back
struct sockaddr saddr;
socklen_t saddr_l = sizeof (saddr);
// here we wait for the reply and fill it into our buffer
i=recvfrom(s,buf,48,0,&saddr,&saddr_l);

//We get 12 long words back in Network order

/*
 * The high word of transmit time is the 4th word we get back
 * tmit is the time in seconds not accounting for network delays which
 * should be way less than a second if this is a local NTP server
 */

 tmit=ntohl((time_t)buf[4]); //# get transmit time

 tmit-= 2208988800U;
 std::cout << "NTP time is " << ctime(&tmit) << std::endl;
 i=time(0);
 std::cout << "System time is " << (i-tmit) << " seconds off" << std::endl;
}

Howto wait for multiple threads in C++

Whenever you have to deal with threads in C++ you should think of using the boost libraries which offer high end solutions for dealing with threads and creating thread-safe applications. A really nice feature on top of this are thread groups which allow you to manage multiple threads very easily. The following code snippet illustrates how to wait for multiple threads using such a thread group.

  #include <boost/thread.hpp>
  #include <boost/thread.hpp>


  void myFunc(int param)
  {
 	std::cout << "Hello world" << std::endl;
  }

  int main()
  {
   int numberOfThreads==4;

   boost::thread_group thread_group;
   
   for(int counter = 0; counter < numberOfThreads;counter++)
       thread_group.add_thread(new boost::thread(myFunc,5));

   thread_group.join_all();

   std::cout << "Done!" << std::endl;
   }

The code executes the function “myFunc” in a separate thread which is added to a thread group. This happens four times. The trick of executing the threads simultaneously is done by the join_all() command. The program waits until the last thread has finished and then is done. There is no magic about threads at all using boost. It is straight-forward and easy.

Wt Web Toolkit: Get URL parameter string values

If you want to access an url parameter string in Witty C++ HTML Web Toolkit there is an easy way to do so. Imagine you want to get the content of the parameter “param” in a URL like http://www.myurl.com/?param=test. To do so you can use the following code in your Wt Application class:


#include &lt;Wt/WApplication&gt;
#include &lt;Wt/WEnvironment&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;

using namespace Wt;

class myApplication: public WApplication
{
public:
  myApplication(const WEnvironment&amp; env)
    : WApplication(env)
  {
    setTitle(&quot;This is an application&quot;);

    addMetaHeader (&quot;description&quot;,&quot;a description&quot;);

    const std::string* param =    this-&gt;environment().getParameter(&quot;param&quot;); 

    if (param!=0)
    {
        std::cout &lt;&lt; (*param) &lt;&lt; std::endl;
    } 
 

 }

}


Also have a look of the handling of internal paths in Wt Web Toolkit:

http://www.webtoolkit.eu/wt/doc/tutorial/wt.html

Wt C++ Web Toolkit: How to send parameters to a slot using the boost::bind routine

Since I did not find any documentation for this in the web: If you are using Wt C++ Web toolkit and ever wondered, how to send parameters to a SLOT() there is a simple solution using the boost::bind routine.

Imagine you have an button, and an event that requires one parameter then you can setup the whole scenario like this:

void MyClass::test(std::string parameter)
{
  cout &lt;&lt; parameter &lt;&lt; endl;
}

WPushButton *button = new WPushButton(&quot;Test&quot;, this);

button-&gt;clicked().connect(boost::bind(&amp;MyClass::test, this, &quot;Hello World!&quot;));

The step which is often forgotten is to put the instance of the class right after the function pointer. (In this case “this”)

Thats it!