Home

GEONius.com
2-Oct-2015
E-mail

port_util - TCP/IP Listening Ports

This web page gets a lot of hits from people searching for some combination of "TCP/IP" and "ports". If you're looking for easy-to-use networking software, see my networking library.

This package implements network listening ports for network servers based on the IOX I/O dispatcher. The server must first create the listening port and then turn control over to the IOX dispatcher:

    #include  <stdio.h>				-- Standard I/O definitions.
    #include  "iox_util.h"			-- I/O event dispatcher definitions.
    #include  "port_util.h"			-- Listening port utilities.
    IoxDispatcher  dispatcher ;
    ListeningPort  port ;
    ...
    ioxCreate (&dispatcher) ;			-- Create I/O event dispatcher.
    ...
    portCreate ("service", NULL, createF, NULL, &port) ;
    ...
    ioxMonitor (dispatcher, -1.0) ;		-- Dispatcher takes over.

When the dispatcher detects a client attempting to connect to the server, it calls an internal PORT_UTIL callback. This callback, portAnswer(), establishes the connection with the client and then calls the client creation function specified in the portCreate() call. The client creation function typically creates some data structure representing the client and registers the new connection with the IOX dispatcher as an input source.

Using the PORT_UTIL package, a simple date/time server requires only a few lines of code:

    #include  <stdio.h>				-- Standard I/O definitions.
    #include  <string.h>			-- Standard C string functions.
    #include  <time.h>				-- Time definitions.
    #include  "port_util.h"			-- Listening port utilities.

    static  int  sendTime (TcpEndpoint connection, IoxDispatcher dispatcher,
                           void *parameter, void **client)
    {   char  *asciiTOD ;
        time_t  binaryTOD = time (NULL) ;

        asciiTOD = ctime (&binaryTOD) ;
        tcpWrite (connection, -1.0, strlen (asciiTOD), asciiTOD, NULL) ;
        tcpDestroy (connection) ;
    }

    int  main (int argc, char *argv[])
    {   IoxDispatcher  dispatcher ;
        ListeningPort  port ;

        portCreate (argv[1], dispatcher, sendTime, NULL, &port) ;
        ioxMonitor (dispatcher, -1.0) ;
    }

Function main() creates the network listening port (whose service name or port number is specified on the command line) and relinquishes control to the IOX I/O dispatcher. When a client requests a connection to the server, the connection is established and sendTime() is called to "create" the client, which, in this case, consists solely of outputting the current time-of-day on the data connection and then closing the connection.


Public Procedures

portCreate() - creates a listening port.
portDestroy() - closes a listening port.

Source Files

port_util.c
port_util.h

(See libnet for the complete source, including support routines and build files.)


Alex Measday  /  E-mail