Socket programming in C on Linux – The Ultimate Guide for Beginners

TCP/IP socket programming in C

This is a quick tutorial on socket programming in c language on a Linux system. "Linux" because the code snippets shown over here will work only on a Linux system and not on Windows. The windows api to socket programming is called winsock and we shall go through it in another tutorial.

Sockets are the "virtual" endpoints of any kind of network communications done between 2 hosts over in a network. For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you. Same with any chat client like gtalk or skype. Any network communication goes through a socket.

The socket api on linux is similar to bsd/unix sockets from which it has evolved. Although over time the api has become slightly different at few places. And now the newer official standard is posix sockets api which is same as bsd sockets.

This tutorial assumes that you have basic knowledge of C and pointers. You will need to have gcc compiler installed on your Linux system. An IDE along with gcc would be great. I would recommend geany as you can quickly edit and run single file programs in it without much configurations. On ubuntu you can do a sudo apt-get install geany on the terminal.

All along the tutorial there are code snippets to demonstrate some concepts. You can run those code snippets in geany rightaway and test the results to better understand the concepts.

1. Create a socket

This first thing to do is create a socket. The socket function does this.
Here is a code sample :

Next we shall try to connect to some server using this socket.
We can connect to www.google.com

Note

Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.

2. Connect socket to a server

We connect to a remote server on a certain port number. So we need 2 things, ip address and port number to connect to.

To connect to a remote server we need to do a couple of things. First is to create a sockaddr_in structure with proper values.

The sockaddr_in has a member called sin_addr of type in_addr which has a s_addr which is nothing but a long. It contains the IP address in long format.

Function inet_addr is a very handy function to convert an IP address to a long format. This is how you do it :

server.sin_addr.s_addr = inet_addr("74.125.235.20");

So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample. A little later on we shall see how to find out the ip address of a given domain name.

The last thing needed is the connect function. It needs a socket and a sockaddr structure to connect to. Here is a code sample.

It cannot be any simpler. It creates a socket and then connects. If you run the program it should show Connected.
Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection.

OK , so we are now connected. Lets do the next thing , sending some data to the remote server.

Connections are present only in tcp sockets

The concept of "connections" apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable "stream" of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by other data.

Other sockets like UDP , ICMP , ARP dont have a concept of "connection". These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.

3. Send data over socket

Function send will simply send data. It needs the socket descriptor , the data to send and its size.
Here is a very simple example of sending some data to google.com ip :

In the above example , we first connect to an ip address and then send the string message "GET / HTTP/1.1\r\n\r\n" to it.
The message is actually a http command to fetch the mainpage of a website.

Now that we have send some data , its time to receive a reply from the server. So lets do it.

Note

When sending data to a socket you are basically writing data to that socket. This is similar to writing data to a file. Hence you can also use the write function to send data to a socket. Later in this tutorial we shall use write function to send data.

4. Receive data on socket

Function recv is used to receive data on a socket. In the following example we shall send the same message as the last example and receive a reply from the server.

We can see what reply was send by the server. It looks something like Html, well IT IS html. Google.com replied with the content of the page we requested. Quite simple!

Note

When receiving data on a socket , we are basically reading the data on the socket. This is similar to reading data from a file. So we can also use the read function to read data on a socket. For example :

read(socket_desc, server_reply , 2000);

Now that we have received our reply, its time to close the socket.

5. Close socket

Function close is used to close the socket. Need to include the unistd.h header file for this.

close(socket_desc);

Thats it.

6. Summary

Your web browser also does the same thing when you open www.google.com
This kind of socket activity represents a socket client. A client is an application that connects to a remote system to fetch or retrieve data.

The other kind of socket application is called a socket server. A server is a system that uses sockets to receive incoming connections and provide them with data. It is just the opposite of Client. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.

Now its time to do some server tasks using sockets. But before we move ahead there are a few side topics that should be covered just incase you need them.

Get ip address of hostname

When connecting to a remote host , it is necessary to have its IP address. Function gethostbyname is used for this purpose. It takes the domain name as the parameter and returns a structure of type hostent. This structure has the ip information. It is present in netdb.h. Lets have a look at this structure

Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application.

This makes it obvious that you cannot have 2 sockets bound to the same port.

2. Listen for incoming connections on the socket

After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function listen is used to put the socket in listening mode. Just add the following line after bind.

So now this program is waiting for incoming connections on port 8888. Dont close this program , keep it running.
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type

We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client.

We can simply use the write function to write something to the socket of the incoming connection and the client should see it. Here is an example :

Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :

$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello Client , I have received your connection. But I have to go now, bye
Connection closed by foreign host.

So the client(telnet) received a reply from server.

We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections.

It means that a server is supposed to be running all the time. Afterall its a server meant to serve. So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept in a loop so that it can receive incoming connections all the time.

So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program.
All telnet terminals would show "Connection closed by foreign host."
Good so far. But still there is not effective communication between the server and the client.

The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time. So now its time to handle the connections , and handle multiple connections together.

6. Handle multiple socket connections with threads

To handle every connection we need a separate handling code to run along with the main server accepting connections.
One way to achieve this is using threads. The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.

On Linux threading can be done with the pthread (posix threads) library. It would be good to read some small tutorial about it if you dont know anything about it. However the usage is not very complicated.

We shall now use threads to create handlers for each connection the server accepts. Lets do it pal.

Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.

The telnet terminals would show :

$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello Client , I have received your connection. And now I will assign a handler for you
Hello I am your connection handler
Its my duty to communicate with you

This one looks good , but the communication handler is also quite dumb. After the greeting it terminates. It should stay alive and keep communicating with the client.

One way to do this is by making the connection handler wait for some message from a client as long as the client is connected. If the client disconnects , the connection handler ends.

The above connection handler takes some input from the client and replies back with the same. Simple! Here is how the telnet output might look

$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello Client , I have received your connection. And now I will assign a handler for you
Greetings! I am your connection handler
Now type something and i shall repeat what you type
Hello
Hello
How are you
How are you
I am fine
I am fine

So now we have a server thats communicative. Thats useful now.

Linking the pthread library

When compiling programs that use the pthread library you need to link the library. This is done like this :

$ gcc program.c -lpthread

Conclusion

By now you must have learned the basics of socket programming in C. You can try out some experiments like writing a chat client or something similar.

If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work then feel free to make a comment below so that it gets fixed.

For some reason, I can not reply to client message (read: Create commands for client to execute specific tasks) as it never gets in to the if (client_message == “help”) however, it does get into the else part of the code (error message)

I think in the connection_handler function, you should clear the client_message, otherwise, it will repeat the sentence last time if your current input is shorter than previous.
Just add one line:
memset(client_message, 0, sizeof(client_message));

hello,there,I have a question about your program, assume that there are two clients connected to the server and the server wants to send messages to the two clients at the same time, will there be any conflict in case the two threads share the same file descriptor?

its just error in test condition…
if(socket_desc == -1) not if( socket_desc = -1)
difference between them is first one testing the equality condition but the second one update the socket_desc value and gives the result the updated value
if the result is non zero if statement executes…
hope it helps..

Check the if statement there. You say “if(socket_desc = -1)” which just sets socket_desc to -1. Setting a variable results in an rvalue that is NOT false, meaning that the if condition will be used every time. Consider writing if statements “if(-1 == socket_desc)” with the constant before the variable. If you only use one equals sign then this will simply result in a compilation error (since you can’t assign a value to a constant number), which is much easier to notice and fix.

Best tutorial for me…
but i found a problem on my machine
recv() function is not working properly for me….
——-Output Start——–
Trying 127.0.0.1…
Connected to localhost.
Escape character is ‘^]’.
Rana is here;Greetings : I am your message handler.
It’s my duty to communicate with you.
Hello
Hello
Another message
Another message
problem
problem
essage
——-end——–
as i send a small message just after a large message it prints out the message with some concatenated text from last message sent

Not sure if you will get or still need this, but for other people who stumble upon this great tutorial, the answer to your question would be to do a call to bzero at the end of the while loop in the connection_handler method. my while loop looks like so:

I am searching for c code in Linux. Where client send message which may be text,audio and video and client can verify that this message is audio message or text message or video message. kindly guide me.

The Tutorial Seems great but am stuck up. I was able to create the
socket but each time I am trying to connect the google server I am
failing and am unable to connect to it.

I am getting a return value of -1 for connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) ;
each time.
Can
any one please help me with that, I am running a Ubuntu 14.04 on
Virtual Machine and I am having internet connection through wifi does it
have any impact on the connection.

Hello this is really great thanks alot, just a simple question, i am able to connect to the server using couple computers on my room, telnet from windows works great too except it doesn’t wait me to press enter it repeats the char as soon as i type it, my question is but what if i wanted to connect from a non local ip address? could you please give me some hints?

Oh nice I understood everything! But I have a question: As long as I’m treating each client with a different thread, how can I make them write something then and show the message to any other client connected? (Basically a chatroom for every client) Don’t know how to do this I’m new at socket programming.

Thanks sir. Such an awesome tutorial. But I need the same for raw sockets. The link you mentioned is just sending data out. How about handling multiple connections using raw socket? I actually want to implement a chat room using raw sockets in C. Any help would be highly appreciated. Just give me idea or tell me the steps to do like the function calls, etc. Thanks :)

Follow us

This site, binarytides.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com.