TCP/IP Sockets Demo 3

Demo 3: Connecting to a socket

This sample program demonstrates how a client establishes a TCP/IP connection to a server. The server listens on a socket and accepts connections. For each connection, it prints the client's address and port and immediately closes the socket.

To run this program, download the demo file and unzip it to create the demo-03 directory. Then compile the file by running make or manually with:

gcc -o client client.c gcc -o server server.c

Then run the server in one window:

./server

You'll see message similar to:

server started on air.pk.org, listening on port 21234

Run the client in another window or on another machine:

./client

You should immediately see a message on the server telling you that a connection was accepted:

received a connection from: 127.0.0.1 port 54744

The server uses the inet_ntoa library function to print the IP address of the client from the address structure that was filled in by the accept system call.

The ./ prefix is there just in case you don't have the current directory in your search path (it's a good security practice not to). If you're on a SunOS (System V) machine, you'll need to link with the socket library by compiling with:

cc -o client client.c -lsocket cc -o server server.c -lsocket

You'll need to edit the makefile and uncomment the LIBS definition.