Linux Network Programming, Part 1

This is the first of a series of articles about how to devlop networked applications using the various interfaces available on Linux.

Like most other Unix-based operating systems, Linux supports TCP/IP as its native network transport. In this series, we will assume you are fairly familiar with C programming on Linux and with Linux topics such as signals, forking, etc.

This article is a basic introduction to using the BSD socket interface for creating networked applications. In the next article, we will deal with issues involved in creating (network) daemon processes. Future articles will cover using remote procedure calls and developing with CORBA/distributed objects.

Brief Introduction to TCP/IP

The TCP/IP suite of protocols allows two applications, running on either the same or separate computers connected by a network, to communicate. It was specifically designed to tolerate an unreliable network. TCP/IP allows two basic modes of operation—connection-oriented, reliable transmission and connectionless, unreliable transmission (TCP and UDP respectively). Figure 1 illustrates the distinct protocol layers in the TCP/IP suite stack.

Figure 1. TCP/IP Protocol Layers

TCP provides sequenced, reliable, bi-directional, connection-based bytestreams with transparent retransmission. In English, TCP breaks your messages up into chunks (not greater in size than 64KB) and ensures that all the chunks get to the destination without error and in the correct order. Being connection-based, a virtual connection has to be set up between one network entity and the other before they can communicate. UDP provides (very fast) connectionless, unreliable transfer of messages (of a fixed maximum length).

To allow applications to communicate with each other, either on the same machine (using loopback) or across different hosts, each application must be individually addressable.

TCP/IP addresses consist of two parts—an IP address to identify the machine and a port number to identify particular applications running on that machine.

The addresses are normally given in either the “dotted-quad” notation (i.e., or as a host name ( The system can use either the /etc/hosts file or the Domain Name Service (DNS) (if available) to translate host names to host addresses.

Port numbers range from 1 upwards. Ports between 1 and IPPORT_RESERVED (defined in /usr/include/netinet/in.h—typically 1024) are reserved for system use (i.e., you must be root to create a server to bind to these ports).

The simplest network applications follow the client-server model. A server process waits for a client process to connect to it. When the connection is established, the server performs some task on behalf of the client and then usually the connection is broken.

Using the BSD Socket Interface

The most popular method of TCP/IP programming is to use the BSD socket interface. With this, network endpoints (IP address and port number) are represented as sockets.

The socket interprocess communication (IPC) facilities (introduced with 4.2BSD) were designed to allow network-based applications to be constructed independently of the underlying communication facilities.

Creating a Server Application

To create a server application using the BSD interface, you must follow these steps:

  1. Create a new socket by typing: socket().

  2. bind an address (IP address and port number) to the socket by typing: bind. This step identifies the server so that the client knows where to go.

  3. listen for new connection requests on the socket by typing: listen().

  4. accept new connections by typing: accept().

Often, the servicing of a request on behalf of a client may take a considerable length of time. It would be more efficient in such a case to accept and deal with new connections while a request is being processed. The most common way of doing this is for the server to fork a new copy of itself after accepting the new connection.

Figure 2. Representation of Client/Server Code

The code example in Listing 1 shows how servers are implemented in C. The program expects to be called with only one command-line argument: the port number to bind to. It then creates a new socket to listen on using the socket() system call. This call takes three parameters: the domain in which to listen to, the socket type and the network protocol.

The domain can be either the PF_UNIX domain (i.e., internal to the local machine only) or the PF_INET (i.e., all requests from the Internet). The socket type specifies the communication semantics of the connection. While a few types of sockets have been specified, in practice, SOCK_STREAM and SOCK_DGRAM are the most popular implementations. SOCK_STREAM provides for TCP reliable connection-oriented communications, SOCK_DGRAM for UDP connectionless communication.

The protocol parameter identfies the particular protocol to be used with the socket. While multiple protocols may exist within a given protocol family (or domain), there is generally only one. For TCP this is IPPROTO_TCP, for UDP it is IPPROTO_UDP. You do not have to explicitly specify this parameter when making the function call. Instead, using a value of 0 will select the default protocol.

Once the socket is created, its operation can be tweaked by means of socket options. In the above example, the socket is set to reuse old addresses (i.e., IP address + port numbers) without waiting for the required connection close timeout. If this were not set, you would have to wait four minutes in the TIME_WAIT state before using the address again. The four minutes comes from 2 * MSL. The recommended value for MSL, from RFC 1337, is 120 seconds. Linux uses 60 seconds, BSD implementations normally use around 30 seconds.

The socket can linger to ensure that all data is read, once one end closes. This option is turned on in the code. The structure of linger is defined in /usr/include/linux/socket.h. It looks like this:

struct linger
        int l_onoff;   /* Linger active */
        int l_linger;  /* How long to linger */

If l_onoff is zero, lingering is disabled. If it is non-zero, lingering is enabled for the socket. The l_linger field specifies the linger time in seconds.

The server then tries to discover its own host name. I could have used the gethostname() call, but the use of this function is deprecated in SVR4 Unix (i.e., Sun's Solaris, SCO Unixware and buddies), so the local function _GetHostName() provides a more portable solution.

Once the host name is established, the server constructs an address for the socket by trying to resolve the host name to an Internet domain address, using the gethostbyname() call. The server's IP address could instead be set to INADDR_ANY to allow a client to contact the server on any of its IP addresses—used, for example, with a machine with multiple network cards or multiple addresses per network card.

After an address is created, it is bound to the socket. The socket can now be used to listen for new connections. The BACK_LOG specifies the maximum size of the listen queue for pending connections. If a connection request arrives when the listen queue is full, it will fail with a connection refused error. [This forms the basis for one type of denial of service attack —Ed.] See sidebar on TCP listen() Backlog.

Having indicated a willingness to listen to new connection requests, the socket then prepares to accept the requests and service them. The example code achieves this using an infinite for() loop. Once a connection has been accepted, the server can ascertain the address of the client for logging or other purposes. It then forks a child copy of itself to handle the request while it (the parent) continues listening for and accepting new requests.

The child process can use the read() and write() system calls on this connection to communicate with the client. It is also possible to use the buffered I/O on these connections (e.g., fprint()) as long as you remember to fflush() the output when necessary. Alternatively, you can disable buffering altogether for the process (see the setvbuf() (3) man page).

As you can see from the code, it is quite common (and good practice) for the child processes to close the inherited parent-socket file descriptor, and for the parent to close the child-socket descriptor when using this simple forking model.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

About TC/IP

Mobile broadband's picture

When we talk about TCp/IP it is a communication protocal for the internet.This is a rule that computers should follow when they communicate over the internet. Your tutorial was useful to go through. I have learned a lot. Thanks for sharing.
Mobile Broadband UK

client and receiver

ha9_009's picture

i send between 2 lab using tcp but the problem is to send file (has a large size ) is not sent completed

excellent article!

Anonymous's picture

All code in this article works PERFECTLY if your computer is configured correctly and you run the programs correctly!

Thanks for an EXCELLENT article.

To those with problems, I suggest learning the following tools:


With these tools you can easily diagnose any problems you run into.

How about an update for IPv6?

Problem in running

Amir's picture

I have a problem when i run your both sample codes(Client and Server).
at first, i ran both, but i saw "connect(): no route to host" error in Client side. Then i checked the received packets by the Wireshark in Server side and i found that the Server replied by a ICMP packet with "destination unreachable : (host administratively prohibited)" content.
after all, i stopped firewalls and ran programs as root at both sides and tried again. but i found "connect(): connection refused" error in Client side. The Server didn't send a ICMP packet in this case.

in both case, i checked the list of opened ports and it seemed that there was nothing wrong.

netstat -an | egrep 'Proto|LISTEN'
tcp 0 0* LIST

thanks in advance


fanaz's picture

hye, i'm a student in comp science in networking. i wanna do the client server application in a cybercafe. but i really dunnow wat software to use such as the suitable programming languange and so on.but i'll doin dis in windows not linux.So I really need ur advice regarding da coding and software suggestion to do this client server application. Do reply me as soon as possible to ma email.thanx for ur advice and cooperation.

sockets is sockets

Anonymous's picture

BSD sockets API is more or less identical on Windows, Solaris, OSX, etc.

Learn it on one and it works on them all.

Good luck sounds like you'll need it.

i need program for........

Anonymous's picture

Design RPC application to add and subtract a given pair of integers
this is my network programming subject whih is my btech final year computerscience
please provide the necessary code and how to execute the same in linux fedaro core 8

thanking you
regards Prasad

oh my

Anonymous's picture

final year in computer science and you can't code a trivial rpc program?

Oh my what have we come to?


Anonymous's picture

i must write a server program that can suport get function in linux by C, can u help me plz?

executing client server socket program that includes pthread

Anonymous's picture

1.i have compiled the program having the thread as gcc server.c -o server -lpthread.
all i need is please help me to run it.
thanks in advance.

socket programming

lalitha's picture

i am trying to connect server using socket in linux but always getting
oops client : connection refused

make sure the server is

Sal's picture

make sure the server is running before you attempt to run the client. If there is nothing to connect to, you will get a similar error.


make sure you are logged in

Sal's picture

make sure you are logged in as root when you run the program. Its most likely the case that you are using raw sockets... for this to run the program as root type in the command: "sudo ./programName" to run the program as root.


network programing and management

vignesh's picture

The CRC program conclude portion complicated for me,o/p is complex for please explain sir.


Anonymous's picture

Suppse the Doble variable num had the vaule 123.4567, what vaul will the following statement assign to num? num= Math.Round(num,2)?

hi.......while working on

hacker's picture

hi.......while working on (client side) network pgm i get segmentation fault...can any one solve it for me..i even changed my port number...but it doesnt works....

bind error during socket programming

jack's picture

i am kinda new to socket programming. wrote the below code for a server. but getting the bind error everytime. i even tried changing the port number(currently is 13 daytime) but doesnt work. please suggest.


int main(int argc,char **argv)
	int listenfd,connfd,retbind;
	struct sockaddr_in servaddr;
	char buff[MAX];
	time_t ticks;
		printf("socket error");
	servaddr.sin_addr.s_addr=htonl(INADDR_ANY); //instead of this use
	if((retbind=bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)))<0)
		printf("bind error %d\n",retbind);
		connfd=accept(listenfd,(struct sockaddr *) NULL,NULL);
return 0;


Anonymous's picture

the problem could be that your interface is not already having bound to the IP address.So try to first configure the interface and then try once again.I think in windows XP if we set ip address in the PC it will automatically configure the interface's value of IP address


salesh's picture

check syntax and parameters of all the function call
related to it.....

bind problem

Anonymous's picture

Hai ,

Good question but you try with the socket numbers more than 8000number

udp socket connection problem

chandan's picture

I am facing problem in implementing client server java program using UDP.
Client is running on Linux machine waiting for msg on a port.
Server is running on Windows machine, sending msg on the same port (On which client is waiting..)
Bur the Client does not receive the msg sent by the Server.

If I run Same Client Server java Program on Linux Machine.. It is working fine.

I want to accomplish the same task using Linux and window machine.
Please help me out...
Thanx in advance..


detect net connection in linux

Poonam's picture

I have another question...
how de we know the internet usage in the computer i.e. the websites URL, time when they were opened, I mean time of the activation/closage of Internet connection.

Is there any api, or any piece of code? I need to do it on linux using c++

thanks in advance

How to test networking function?

Anonymous's picture

I need to test netwoking functions like, socket, connect, send, sendto, receive, receivefrom, bind, close, SetSockOpt etc. Is there any standard test case script or document for testing networking functions? If you have please send me. If there is any simple sample application which can test all the functions with all the possible scenarios, please let me know about it. I'm trying to write a application which test all the functions of networking. Please help me regarding this.

Re ; test network functions

Anonymous's picture

all the network functions lik connect,accept,bind etc.. return a -1 on failure, so u can check if it didnt work properly by using a simple if condition. i suggest using read() and write() instead of send() and recv(), read and write will again throw an output <0 if it failed, so u can check data being sent or recieved by using if(read() <0) then print("failed").

hope this helps.

How to connect windows to linux using socket prograaming

Anonymous's picture

please tell me how cam i send messages from linux to windows

I am interested too

Anonymous's picture

I am interested too

socket problem

Anonymous's picture

what are the reasons for error .....


while connecting from linux to windows sockets..

Client-Manager-Server Applications

allan's picture

To Whom It May Concern:

Good day!
Instead of comments, I will ask for you advice on Socket Programming -> passing socket file descriptor from client to manager which in turn passes the client socket to the server but the server should communicate directly to the server using its socket file descriptor (i.e. write(client_sockfd,...m...). It did not work for me. Is it possible to communicate the server directly to client?

I need you help badly. I will thank you in advance for any help you can give.


problems in multithreaded send()/recv() using tcp socket

arslan's picture

i am implementing a multithread ftp server in linux which will work like a download accelerator.
when a client connects to server ,four tcp connection sockets are established between a client and the server using four means that 4 thread are on server side ,each sending 1/4th of the file ,each thread using single send(),and four threads on client side, each reciveing 1/4th of the file,each thread using single recv(). file is broken down in four parts.using for loop, each part are sent in the chunks of 1024 bytes append with their seqeunce number .similarly the file is recieved by four threads ,each thread using for loop and in the for loop ä single recv() is used and recieved data in written on single file.

the server sends the complete file correctly and exits the thread function correctly , the connections are not closed yet .but the client doesnot revcive all the packets and one of the thread on clients side gets stuck.
where is the problem? is it the flow control? but doesnot tcp sockets take care flow and error control???
if I add two consecutive send() commands after the one recv()in each thread of client and in these two send() i send dummy packets. and on server side i add two recv() after the one send()in each thread problem is kind of solved but delayed is increased considerably and this is not good solution....i want to know what the exact problem is , the reason behind it,and its solution tooooo

how to pass structures in sockets

narsi's picture


Could you please help in socket programming.

how to pass structures in sockets.

Thanks & Regards,

Need Help!!!!

Sunny's picture

I have a question How can I detect that the connect is lost by just modifier tcp server.
Right now I use timeout to detect that but that make me to send and recv data all the time.

If any one know how do that please tell me and is it have any article about this please tell me

Thank you

Weird Problem

brad.maillist's picture


let me start off by saying that I found your article to be very helpful. I am new to this so forgive my question, but I have copied out the server code and I am able to compile it using gcc v4.1.0 on Suse 10.1 but when I try to run the code, i get a segmentation fault around the line where argv[1] is assigned to port. I cannot for the life of me figure this out since all the documentation I have read implies that there should not be a problem here.

Thanks for your help

Weird solution

NeoKuaho's picture

I can only imagine that when you run the program,
you just enter the program (Server) name and hit enter...?

on the command line, you must also provide a port number since the program is expecting it.

Remember, argv[0] //Is the program's name
argv[1]// is the first parameter after the program name.

try : server 3009

I hope this helps.

Im not the author but if I

Anonymous's picture

Im not the author but if I were you I would verify that the port
is being passed through "atoi" before being assigned to the port variable...

if that is the case then I would test out all arguments before the tcp stuff is called to verify how the arguments are being passed to the program.

I would also check to see if you need to use "htons" on the port because of "endian" problems. i.e. x86 integers are stored lsb -> msb whereas most other processors use msb -> lsb format...

Regarding Difference between TCP / UDP

Sudhir's picture


i have a query regarding the difference between TCP & UDP from developers pint of view at coding level how can we diffentiate between TCP & UDP if both use Socket,bind,listen,send recv

at the transport layer how does it diffentiate between TCP & UDP

Thankxx in advance


Regarding Difference between TCP / UDP

Chandra's picture


The diffrence lies with the connect() system call.In client side for TCP the connect() system call is used for reliable connection,but there is no such type of call in UDP side, as it is connection less.


errata for Listing 4

Ivan_Griffin's picture


Thanks to "StratBoy SixtyOne" for point out a typo in one of the file listings to me (6 years after it was written - great to see people still interested in the article and code).

The clientLength parameter should be set to sizeof(clientName) before the recvfrom() call.

Best Regards,

How to get the best route

Pal's picture

Pls help me figure out how to programmatically find the best route to a destination in Linux C.

Thanks in advance

help on socket programming

vikram's picture

Hi ,
Could you please help in solving following problem :

1. My Application (huge open source !!1 )is having 2 threads having 2 different UDP sockets , bind on two different ports.( Lets give them name port1 and port2)

2. port1 can send and receive pkts from any device

3. How ever If port2 is in communication with some other device(sending receiving pkts) , and If any other client sends packet to this port2, It got ICMP unrechable .
Why this is happening ? i could not found in code any setting which will cause this to happen . I want to accept packets from source other then
those whom sending to. ( Packet are reaching till devic but discarded with ICMP unreachable)

Thanks in Advance

best regards


The Icmp unreachable is

Lolo's picture

The Icmp unreachable is written by the UDP stack.
This happens when no prog are listenning on the port.
May be, your prog is not listenning anymore when it accepts a communication.

This is a pretty good stuff

Narenderan Perumal's picture

This is a pretty good stuff to start with socket programming.

Re: Linux Network Programming, Part 1

Anonymous's picture

Somebody should get with the times.

In this page, you reciprocate the information provided in the Linux
manual page for the listen(2) syscall, stating that BSD *still*
limits this value to 5. It's limited to whatever SOMAXCONN is
set to (indeed, somaxconn, which is a static int initialized to
SOMAXCONN). In FreeBSD, this value is 128 by default.

Yeah! Way to stick it to the

Anonymous's picture

Yeah! Way to stick it to the authors of an article published SIX YEARS BEFORE YOU COMMENTED. You're so much better than they are for "getting with the times!" We bow before you!

Re: Linux Network Programming, Part 1

Anonymous's picture

I'd love to see a simple demonstration like this on how to use threads instead of processes. Are they much more complicated?

Re: Linux Network Programming, Part 1

Anonymous's picture

The answer to that (like most things in computer science) is yes and no. It depends on how much you get into sharing memory (or other resources) between threads. Multithreading itself is not a dificult topic... it is the topic of synchronization that is a little difficult... however, the two are very closely related.

If you are interested in learning about threads do a search on the pthreads library. There is an implementation for windows as well as most unix flavors including linux.

Re: Linux Network Programming, Part 1

Anonymous's picture

what an article?great,excellent to read this.thanks for the author...helped me a lot but one prob..explaining each and every line of the program thru comment statements would be helpful to understand the concepts fully thanks
anand hariharan

Re: Linux Network Programming, Part 1

Anonymous's picture

Good article, well written. A nice easy way to learn sockets. Are there more of these articles by the same authors?

Re: Linux Network Programming, Part 1

Anonymous's picture

I wonder if there is anywhere that you can find a tutorial on handling ICMP. that would be nice.

Re: Linux Network Programming, Part 1

Anonymous's picture

Very helpful article. I am converting for MS Sockets and this re-enforces how similar (identical!) they are. Thank you.

Re: Linux Network Programming, Part 1

Anonymous's picture

IIRC Microsoft lifted the BSD implementation verbatim. I think it even shows up somewhere in the system during bootup or something.

Geek Guide
The DevOps Toolbox

Tools and Technologies for Scale and Reliability
by Linux Journal Editor Bill Childers

Get your free copy today

Sponsored by IBM

Upcoming Webinar
8 Signs You're Beyond Cron

Scheduling Crontabs With an Enterprise Scheduler
11am CDT, April 29th
Moderated by Linux Journal Contributor Mike Diehl

Sign up now

Sponsored by Skybot