Set up and listen

listen (listenfd, 5) ; <1-1 on socket while (!done) {

printf("Waiting for connection\n");

bzero(&tv,sizeof(tv)); tv.tv_sec = 2 ; FD_ZERO(Sreadset); FD_SET(listenfd, Sreadset);

result = select(listenfd + 1, &readset, &readset, NULL, &tv) ; if (result >= 1)

printf("Incoming connection!\n"); break;

printf("Timeout.\n"); continue;

else printf("Error, leave.\n"); return result;

printf("Calling accept:\n");

connfd = accept (listenfd, © Accept S°cket

(struct sockaddr *) NULL, NULL); <-' connection printf("Connecting\n"); ticks = time (NULL) ;

sprintf(buf,"%.24s",ctime(Sticks)); printf("sending [%s]\n",buf); write(connfd,buf,strlen(buf)); close(connfd);

return 0;

As with many C language applications, a number of headers O are required, including definitions and prototypes for time functions, SQLite functions, and of course a number of headers required for TCP sockets. Note that the sqlite3.h header file is not provided in the CodeSourcery tool chain. This file was acquired from a sqlite3 distribution, and the file was copied into the local directory along with daytime.c. This is why the include file is delimited with quotation marks rather than <>, which is used for finding include files in the system or compiler path. The htons function is typically implemented in the library named socket ( Android does not provide this library, nor was this found in any of the system libraries. Therefore htons is defined here as a macro ©. This macro is required to get the network byte ordering correct. When the application is running, this port can be verified by running netstat -tcp on the command line in the adb shell.

The standard TCP port for a daytime server is port 13. In ©, application is using port 1024 because our application cannot bind to any port numbered 1023 or below. Only system processes may bind to ports below 1024.

In the RecordHit function, we see SQLite interaction ©. The RecordHit() function is responsible for inserting a record into the SQLite database created for this application.

Jumping into the main function, we see the socket functions in use to listen on a socket for incoming connections When a connection is accepted ©, the current system time is sent to the calling client. After this, the application makes a record of the transaction by calling the RecordHit function ©.

That's all the code necessary to implement our Android/Linux Daytime Server application. Let's look next at the SQLite3 database interaction in more detail.

0 0

Post a comment