UNIX Sockets Tutorial

Using sockets to communicate across the Internet is relativly painless. All it takes is a little start-up time and your in buisness.


Sockets are based on the client/server model. I'll cover the client side first.

First make a socket. The function that does this is socket(). It takes three parameters the first is always AF_INET, and the second is always SOCK_STREAM.  This means that it is an Internet stream socket. The third parameter is the protocol, I suggest using IPPROTO_TCP since it provides all sorts of useful features for us.  This function returns a socket handle or -1 if there is an error.

Once a socket is made we need to connect to a server.  The server is identified by an address/port pair. So we fill a sockaddr_in stuct with the right info and call connect(), which returns a -1 if an error occurs.  Don't worry, I'll show you code examples and you can read the man pages for a better understanting of what's going on. A port can be any number between 1000 and 64000

Then all we need to do is read() and write() to the socket, just like a file. When we are done with the socket, we call close().

Ok, here is the code sample: client.c


The server side is a little more tricky, but not much.

It starts out the exact same. Make a socket using socket() with the same parameters.

Then it needs to be bound to a port. This is done using the bind() function.  It takes the same parameters as connect. All you need to do is set the family, port, and address. The family is the same, and the port is the same, the address is INADDR_ANY. And it will set up a port with the given number and it will be bound to the socket.

Then the listen queue is established with listen(). The first parameter is the socket and the second is the size of the listen queue.

You accept the queued connections with accept(), which returns a socket handle which can be writen and read from just like the client sockets.

Here is the sample code: server.c


That is all there is to it. Look at the man pages on the functions for more information.