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.
Connectionless Data—UDP

Listing 4 shows a connectionless server using UDP. While UDP applications are similar to their TCP cousins, they have some important differences. Foremost, UDP does not guarantee reliable delivery—if you require reliability and are using UDP, you either have to implement it yourself in your application logic or switch to TCP.

Like TCP applications, with UDP you create a socket and bind an address to it. (Some UDP servers do not need to call bind(), but it does no harm and will save you from making a mistake.) UDP servers do not listen or accept incoming connections, and clients do not explicitly connect to servers. In fact, there is very little difference between UDP clients and servers. The server must be bound to a known port and address only so that the client knows where to send messages. Additionally, the order of expected data transmissions is reversed, i.e., when you send data using send() in the server, your client should expect to receive data using recv().

It is common for UDP clients to fill in the sockaddr_in structure with a sin_port value of 0. (Note that 0 in either byte-order is 0.) The system then automatically assigns an unused port number (between 1024 and 5000) to the client. I'm leaving it as an exercise to the reader to convert the server in Listing 4 into a UDP client.

/etc/services

In order to connect to a server, you must first know both the address and port number on which it is listening. Many common services (FTP, TELNET, etc.) are listed in a text database file called /etc/services. An interface exists to request a service by name and to receive the port number (correctly formatted in network byte-order) for that service. The function is getservbyname(), and its prototype is in the header file /usr/include/netdb.h. This example takes a service name and protocol type and returns a pointer to struct servent.

struct servent
{
        char *s_name;   /* official service name */
        char **s_aliases;       /* alias list */
        int s_port;     /* port number, network<\n>
                         * byte-order--so do not
                         * use host-to-network macros */
        char *s_proto;  /* protocol to use */
};
Conclusions

This article has introduced network programming in Linux, using C and the BSD Socket API. In general, coding with this API tends to be quite laborious, especially when compared to some of the other techniques available. In future articles, I will compare two alternatives to the BSD Socket API for Linux: the use of Remote Procedure Calls (RPCs) and the Common Object Request Broker Architecture (CORBA). RPCs were introduced in Ed Petron's article “Remote Procedure Calls” in Linux Journal Issue #42 (October, 1997).

Resources

TCP listen() Backlog

Major System Calls The next article in this series will cover the issues involved in developing long-lived network services (daemons) in Linux.

All listings referred to in this article are available by anonymous download in the file ftp://ftp.linuxjournal.com/lj/listings/issue46/2333.tgz.

Ivan Griffin (ivan.griffin@ul.ie) is a research postgraduate student in the ECE department at the University of Limerick, Ireland. His interests include C++/Java, WWW, ATM, the UL Computer Society (http://www.csn.ul.ie/) and, of course, Linux (http://www.trc.ul.ie/~griffini/linux.html).

Dr. John Nelson (john.nelson@ul.ie) is a senior lecturer in Computer Engineering at the University of Limerick. His interests include mobile communications, intelligent networks, Software Engineering and VLSI design.

______________________

Comments

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:

gdb
netstat
tcpdump
lsof
valgrind

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

How about an update for IPv6?

Problem in running

Amir's picture

Hello
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 127.0.0.1:4000 0.0.0.0:* LIST

thanks in advance

inquiries

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?

question

Anonymous's picture

hi
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.

Sal

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.

Sal

network programing and management

vignesh's picture

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

Math.Round

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.

#include"header.h"

int main(int argc,char **argv)
{
	int listenfd,connfd,retbind;
	struct sockaddr_in servaddr;
	char buff[MAX];
	time_t ticks;
	
	if((listenfd=socket(AF_INET,SOCK_STREAM,0))<0)
	{
		printf("socket error");
		exit(1);
	}
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family=AF_INET;
	servaddr.sin_addr.s_addr=htonl(INADDR_ANY); //instead of this use
	servaddr.sin_port=htons(13);
	
	if((retbind=bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)))<0)
	{
		printf("bind error %d\n",retbind);
		exit(1);
	}
	listen(listenfd,1024);
	for(;;)
	{
		connfd=accept(listenfd,(struct sockaddr *) NULL,NULL);
		ticks=time(NULL);
		snprintf(buff,sizeof(buff),"%s\r\n",ctime(&ticks));
		write(connfd,buff,strlen(buff));
		close(connfd);
	}
return 0;
}

reply

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

information

salesh's picture

hi.........
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

MailID:ur_mohanreddy@yahoo.co.in

udp socket connection problem

chandan's picture

hi,
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..

chandan

detect net connection in linux

Poonam's picture

Hi,
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 .....

WSAGetLastError()=10061

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.

Regards,
Allan

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.
discription:
when a client connects to server ,four tcp connection sockets are established between a client and the server using four threads.it 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.

Problem
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 ........my 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

hi,

Could you please help in socket programming.

how to pass structures in sockets.

Thanks & Regards,
Narsi.

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

Hello,

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

hi

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

Sudhir

Regarding Difference between TCP / UDP

Chandra's picture

Hi,

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.

Thanks

errata for Listing 4

Ivan_Griffin's picture

Hi,

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,
Ivan.

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
Pal

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

Vikram

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.
Thanks
~Naren

Re: Linux Network Programming, Part 1

Anonymous's picture

Somebody should get with the times.

http://www.linuxjournal.com/modules.php?op=modload&name=NS-lj-issues/iss...

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.

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix