Basic Network Programming with Sockets

A socket is an abstraction for various types of communication mechanisms. In its most common use, a socket is an interface to a TCP/IP bidirectional communication channel.

Phone Calls

A TCP/IP channel is like a telephone. Like in a phone call, there are two distinct roles in setting up a link. One party--the caller (or client)--initiates the connection while the other party--the receiver (or server)--waits for incoming calls, listening to the ringer. Here are the sequences of basic operations performed by servers and client when setting up, using, and shutting down a connection:
phone call TCP/IP socket
server install a telephone create a socket (and bind it to a specific port)
wait for incoming calls listen to the socket
when the phone rings, pick up the phone accept a connection
bla bla... aha... read from/write into the socket
hang up close (or shutdown) the socket
client install a telephone, create a socket
pick up the phone and dials a number connects the socket to the server's address
...aha... bla bla... aha... read from/write into the socket
hang up close (or shutdown) the socket

TCP/IP Communication in C/C++ and JavaTM

The Berkeley socket API is the most common interface to network services, and particularly TCP/IP channels, for the C and C++ languages under more or less any UNIX system. Other analogous interfaces for the C and C++ languages are available under other operating systems. The most common one is the WinSock interface of win32 systems (Windows95, Windows98, and WindowsNT).

Internet network services such as TCP/IP channels are available to the JavaTM language programmer through the java.net package of the Java Development Kit.

The following code examples are server and client skeletons implemented in C/C++, using the Berkeley socket API, and in JavaTM, using the java.net package. Notice that these examples do not handle errors. Chunks of introductory code are also necessary to include the appropriate header files (in C++) or to import the appropriate classes (in JavaTM).

Server

C/C++

void server(unsigned int port) 
{
    int                 ssock;      // file descriptor of the socket
    struct sockaddr_in  addr;       // address (local port)

    // create the socket
    int ssock = socket(PF_INET, SOCK_STREAM, 0);

    // set the address to a local port (variable `port')
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(port);

    // bind the socket to the local port
    bind(ssock, (struct sockaddr *)&addr, sizeof(addr));

    // listen to the socket
    listen(fd, SOMAXCONN);
    
    // accept connections
    do {
        int                 new_conn;  // file descriptor of the connection
	struct sockaddr_in  caddr;     // address of the client
	int                 caddrlen;  // length of the address

	caddrlen = sizeof(caddr);
        new_conn = accept(ssock, (struct sockaddr *)&caddr, &caddrlen);
	//
        // do something with new_conn
        //

	// closes new_conn
        close(new_conn);
    } while ( /* some condition */ );

    // closes the server socket
    close(ssock);
}

JavaTM

//...
public static void server(int port)
{
    ServerSocket ssock;               // server socket 

    ssock = new ServerSocket(port);   // created, and bound to local port
    do {
        Socket new_conn;              // new connection
        new_conn = ssock.accept();    // accepts new connections
	//
        // do something with new_conn
	//
    } while (/* some condition */);
}

Client

C/C++

void client(const char* host, unsigned short port)
{
    int                 csock;
    struct sockaddr_in  addr;

    // creates the socket
    csock = socket(PF_INET, SOCK_STREAM, 0);
  
    // sets the destination address
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);

    struct hostent * host_entry;
    host_entry = gethostbyname(host);
    memcpy(&addr.sin_addr, host_entry->h_addr, host_entry->h_length);

    // connects the socket
    connect(csock, (struct sockaddr *)&addr, sizeof(addr));
    //
    // do something with csock
    //

    // closes the connection
    close(csock);
}

JavaTM

//...
public static void client(String host, int port)
{
    Socket csock;                     // client socket 

    csock = new Socket(InetAddress.getByName(host),port);
    //
    //  do something with csock
    //
}

Documentation

You can find lots of documentation describing the Berkeley socket API or the java.net package on-line. See for example: BSD Sockets: A Quick And Dirty Primer, Network Programming and the Berkeley Sockets, and JavaTM 2 Platform, Standard Edition, v1.2.2 API Specification: Package java.net

Under most UNIX systems, all the system calls of the socket API are described by on-line manual pages (e.g., man socket tells you everything you need to know about the socket() function). For JavaTM, you can consult the Java Development Kit Documentation available with your installation or on-line.


this page is maintained by Antonio Carzaniga, last update: Jan 2000