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 :
#include<stdio.h> #include<sys/socket.h> int main(int argc , char *argv[]) { int socket_desc; socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } return 0; }
Function socket() creates a socket and returns a descriptor which can be used in other functions. The above code will create a socket with following properties
Address Family - AF_INET (this is IP version 4) Type - SOCK_STREAM (this means connection oriented TCP protocol) Protocol - 0 [ or IPPROTO_IP This is IP protocol]
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.
struct sockaddr_in server;
Have a look at the structure
// IPv4 AF_INET sockets: struct sockaddr_in { short sin_family; // e.g. AF_INET, AF_INET6 unsigned short sin_port; // e.g. htons(3490) struct in_addr sin_addr; // see struct in_addr, below char sin_zero[8]; // zero this if you want to }; struct in_addr { unsigned long s_addr; // load with inet_pton() }; struct sockaddr { unsigned short sa_family; // address family, AF_xxx char sa_data[14]; // 14 bytes of protocol address };
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.
#include<stdio.h> #include<sys/socket.h> #include<arpa/inet.h> //inet_addr int main(int argc , char *argv[]) { int socket_desc; struct sockaddr_in server; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } server.sin_addr.s_addr = inet_addr("74.125.235.20"); server.sin_family = AF_INET; server.sin_port = htons( 80 ); //Connect to remote server if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0) { puts("connect error"); return 1; } puts("Connected"); return 0; }
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 :
#include<stdio.h> #include<string.h> //strlen #include<sys/socket.h> #include<arpa/inet.h> //inet_addr int main(int argc , char *argv[]) { int socket_desc; struct sockaddr_in server; char *message; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } server.sin_addr.s_addr = inet_addr("74.125.235.20"); server.sin_family = AF_INET; server.sin_port = htons( 80 ); //Connect to remote server if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0) { puts("connect error"); return 1; } puts("Connected\n"); //Send some data message = "GET / HTTP/1.1\r\n\r\n"; if( send(socket_desc , message , strlen(message) , 0) < 0) { puts("Send failed"); return 1; } puts("Data Send\n"); return 0; }
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.
#include<stdio.h> #include<string.h> //strlen #include<sys/socket.h> #include<arpa/inet.h> //inet_addr int main(int argc , char *argv[]) { int socket_desc; struct sockaddr_in server; char *message , server_reply[2000]; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } server.sin_addr.s_addr = inet_addr("74.125.235.20"); server.sin_family = AF_INET; server.sin_port = htons( 80 ); //Connect to remote server if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0) { puts("connect error"); return 1; } puts("Connected\n"); //Send some data message = "GET / HTTP/1.1\r\n\r\n"; if( send(socket_desc , message , strlen(message) , 0) < 0) { puts("Send failed"); return 1; } puts("Data Send\n"); //Receive a reply from the server if( recv(socket_desc, server_reply , 2000 , 0) < 0) { puts("recv failed"); } puts("Reply received\n"); puts(server_reply); return 0; }
Here is the output of the above code :
Connected Data Send Reply received HTTP/1.1 302 Found Location: http://www.google.co.in/ Cache-Control: private Content-Type: text/html; charset=UTF-8 Set-Cookie: PREF=ID=0edd21a16f0db219:FF=0:TM=1324644706:LM=1324644706:S=z6hDC9cZfGEowv_o; expires=Sun, 22-Dec-2013 12:51:46 GMT; path=/; domain=.google.com Date: Fri, 23 Dec 2011 12:51:46 GMT Server: gws Content-Length: 221 X-XSS-Protection: 1; mode=block X-Frame-Options: SAMEORIGIN <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>302 Moved</TITLE></HEAD><BODY> <H1>302 Moved</H1> The document has moved <A HREF="http://www.google.co.in/">here</A>. </BODY></HTML>
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
So in the above example we learned how to
1. Create a socket 2. Connect to remote server 3. Send some data 4. Receive a reply
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
/* Description of data base entry for a single host. */ struct hostent { char *h_name; /* Official name of host. */ char **h_aliases; /* Alias list. */ int h_addrtype; /* Host address type. */ int h_length; /* Length of address. */ char **h_addr_list; /* List of addresses from name server. */ };
The h_addr_list
has the IP addresses. So now lets have some code to use them.
#include<stdio.h> //printf #include<string.h> //strcpy #include<sys/socket.h> #include<netdb.h> //hostent #include<arpa/inet.h> int main(int argc , char *argv[]) { char *hostname = "www.google.com"; char ip[100]; struct hostent *he; struct in_addr **addr_list; int i; if ( (he = gethostbyname( hostname ) ) == NULL) { //gethostbyname failed herror("gethostbyname"); return 1; } //Cast the h_addr_list to in_addr , since h_addr_list also has the ip address in long format only addr_list = (struct in_addr **) he->h_addr_list; for(i = 0; addr_list[i] != NULL; i++) { //Return the first one; strcpy(ip , inet_ntoa(*addr_list[i]) ); } printf("%s resolved to : %s" , hostname , ip); return 0; }
Output of the code would look like :
www.google.com resolved to : 74.125.235.20
So the above code can be used to find the ip address of any domain name. Then the ip address can be used to make a connection using a socket.
Function inet_ntoa
will convert an IP address in long format to dotted format. This is just the opposite of inet_addr
.
So far we have see some important structures that are used. Lets revise them :
1. sockaddr_in
- Connection information. Used by connect , send , recv etc.
2. in_addr
- Ip address in long format
3. sockaddr
4. hostent
- The ip addresses of a hostname. Used by gethostbyname
In the next part we shall look into creating servers using socket. Servers are the opposite of clients, that instead of connecting out to others, they wait for incoming connections.
Socket server
OK now onto server things. Socket servers operate in the following manner
1. Open a socket 2. Bind to a address(and port). 3. Listen for incoming connections. 4. Accept connections 5. Read/Send
We have already learnt how to open a socket. So the next thing would be to bind it.
1. Bind socket to a port
The bind function can be used to bind a socket to a particular "address and port" combination. It needs a sockaddr_in structure similar to connect function.
int socket_desc; struct sockaddr_in server; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 8888 ); //Bind if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) { puts("bind failed"); } puts("bind done");
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.
//Listen listen(socket_desc , 3);
Thats all. Now comes the main part of accepting new connections.
3. Accept connection
Function accept
is used for this. Here is the code
#include<stdio.h> #include<sys/socket.h> #include<arpa/inet.h> //inet_addr int main(int argc , char *argv[]) { int socket_desc , new_socket , c; struct sockaddr_in server , client; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 8888 ); //Bind if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) { puts("bind failed"); } puts("bind done"); //Listen listen(socket_desc , 3); //Accept and incoming connection puts("Waiting for incoming connections..."); c = sizeof(struct sockaddr_in); new_socket = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c); if (new_socket<0) { perror("accept failed"); } puts("Connection accepted"); return 0; }
Program output
Run the program. It should show
bind done Waiting for incoming connections...
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
$ telnet localhost 8888
On the terminal you shall get
Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Connection closed by foreign host.
And the server output will show
bind done Waiting for incoming connections... Connection accepted
So we can see that the client connected to the server. Try the above process till you get it perfect.
4. Get the ip address of the connected client
You can get the ip address of client and the port of connection by using the sockaddr_in structure passed to accept function. It is very simple :
char *client_ip = inet_ntoa(client.sin_addr); int client_port = ntohs(client.sin_port);
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 :
#include<stdio.h> #include<string.h> //strlen #include<sys/socket.h> #include<arpa/inet.h> //inet_addr #include<unistd.h> //write int main(int argc , char *argv[]) { int socket_desc , new_socket , c; struct sockaddr_in server , client; char *message; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 8888 ); //Bind if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) { puts("bind failed"); return 1; } puts("bind done"); //Listen listen(socket_desc , 3); //Accept and incoming connection puts("Waiting for incoming connections..."); c = sizeof(struct sockaddr_in); new_socket = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c); if (new_socket<0) { perror("accept failed"); return 1; } puts("Connection accepted"); //Reply to the client message = "Hello Client , I have received your connection. But I have to go now, bye\n"; write(new_socket , message , strlen(message)); return 0; }
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.
5. Live Server
So a live server will be alive for all time. Lets code this up :
#include<stdio.h> #include<string.h> //strlen #include<sys/socket.h> #include<arpa/inet.h> //inet_addr #include<unistd.h> //write int main(int argc , char *argv[]) { int socket_desc , new_socket , c; struct sockaddr_in server , client; char *message; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 8888 ); //Bind if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) { puts("bind failed"); return 1; } puts("bind done"); //Listen listen(socket_desc , 3); //Accept and incoming connection puts("Waiting for incoming connections..."); c = sizeof(struct sockaddr_in); while( (new_socket = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) ) { puts("Connection accepted"); //Reply to the client message = "Hello Client , I have received your connection. But I have to go now, bye\n"; write(new_socket , message , strlen(message)); } if (new_socket<0) { perror("accept failed"); return 1; } return 0; }
We havent done a lot there. Just the accept was put in a loop.
Now run the program in 1 terminal , and open 3 other terminals. From each of the 3 terminal do a telnet to the server port.
Each of the telnet terminal would show :
$ 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
And the server terminal would show
bind done Waiting for incoming connections... Connection accepted Connection accepted Connection accepted
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.
#include<stdio.h> #include<string.h> //strlen #include<stdlib.h> //strlen #include<sys/socket.h> #include<arpa/inet.h> //inet_addr #include<unistd.h> //write #include<pthread.h> //for threading , link with lpthread void *connection_handler(void *); int main(int argc , char *argv[]) { int socket_desc , new_socket , c , *new_sock; struct sockaddr_in server , client; char *message; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 8888 ); //Bind if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) { puts("bind failed"); return 1; } puts("bind done"); //Listen listen(socket_desc , 3); //Accept and incoming connection puts("Waiting for incoming connections..."); c = sizeof(struct sockaddr_in); while( (new_socket = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) ) { puts("Connection accepted"); //Reply to the client message = "Hello Client , I have received your connection. And now I will assign a handler for you\n"; write(new_socket , message , strlen(message)); pthread_t sniffer_thread; new_sock = malloc(1); *new_sock = new_socket; if( pthread_create( &sniffer_thread , NULL , connection_handler , (void*) new_sock) < 0) { perror("could not create thread"); return 1; } //Now join the thread , so that we dont terminate before the thread //pthread_join( sniffer_thread , NULL); puts("Handler assigned"); } if (new_socket<0) { perror("accept failed"); return 1; } return 0; } /* * This will handle connection for each client * */ void *connection_handler(void *socket_desc) { //Get the socket descriptor int sock = *(int*)socket_desc; char *message; //Send some messages to the client message = "Greetings! I am your connection handler\n"; write(sock , message , strlen(message)); message = "Its my duty to communicate with you"; write(sock , message , strlen(message)); //Free the socket pointer free(socket_desc); return 0; }
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.
So the connection handler can be rewritten like this :
/* * This will handle connection for each client * */ void *connection_handler(void *socket_desc) { //Get the socket descriptor int sock = *(int*)socket_desc; int read_size; char *message , client_message[2000]; //Send some messages to the client message = "Greetings! I am your connection handler\n"; write(sock , message , strlen(message)); message = "Now type something and i shall repeat what you type \n"; write(sock , message , strlen(message)); //Receive a message from client while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 ) { //Send the message back to client write(sock , client_message , strlen(client_message)); } if(read_size == 0) { puts("Client disconnected"); fflush(stdout); } else if(read_size == -1) { perror("recv failed"); } //Free the socket pointer free(socket_desc); return 0; }
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.
how udp working..
A great tutorial.
thank u very much.
how to implement firewall in linux….i dont wanna use iptables….??any good links or tutorials…????
thanks for ur xcellent tutorial….keep on going
That’s great! Thank you
Excellent tutorials!
Thanks, I was able to understand this easily
Thanks Mr
how to connect with other systems in the room using sockets…there we need to specify just the ipaddress of the system….please clarify
first you need to run a socket server on the other machines that open a certain port N.
then on your computer you have to run the socket client, and give it the ip address of the other machine and the port number N to connect.
Hello,thank you for this tutorial , it was very useful! Just one question:
I’m trying to write a program that connects to itself , create a client and server and then sends a string and prints to from the server. I searched through the net and saw that instead of using inet_addr(site IP) you can use htol(INADDR_ANY) , but this creates an error when connecting the socket. Any tips?
i am not aware of any socket function called htol. How are you coding it ?
pastebin your code and show.
I have a problem, when I compiled & run it just said connect error. why??
show the exact code you are using
paste your code on https://gist.github.com/ or http://pastebin.com/
and give the link.
your first example of connecting to Google server…
It just said ———-connection error
I know this is a bit late, (but for other readers), just open up a terminal and type “ping google.com” then copy that IP address and pass that argument in the “inet_addr()” function. See if that works.
very nice thank you
Wanted to learn socket programming which is basic & easy, I feel like I am taught this lesson by a teacher, feel like going to school again & learning lessons all over, oh those childhood days, I miss every inch of it though it used to pinch but I really miss that inch!!
great tutorial! thanks =)
Thank you very much, Mr. Silver Moon.
FW
If this is a tutorial for Beginners, then I wonder why I have so many unanswered questions as a beginner? Please help to answer my questions:
1. What are the variables argc and *argv[] used for later?
2. What do the sin_ represent? sa_? s_?
3. Is inet_addr a built-in function? htons()? htons(3490)? where did 3490 come from? Waht is it?
4. In inet_addr(“74.125.235.20”) , where did these numbers come from?
If anyone to help answer these, will be appreciated. Thanks.
FW
1. the variables argc/argv are for commandline arguments, can be used for anything.
2. check the structures called sockaddr and sockaddr_in. The sa_ and s_ are members of those structures. The structures are used to hold address information for a socket. The address information contains 3 main parameters, name address family AF_INET, Ip address and port number.
3. Yes inet_addr is a built in function. The 3490 is an arbitrary port number, it can be any number between 1024 and 65535.
4. 75.125.235.20 is the ip address of google.com
you can use any ip address of your choice.
Nice tutorial
thanks a lot
use proper header files.. @49168c6a3db8329cba3f54d539f810f9:disqus
i am getting an error
“socket_client.c:(.text+0x13e): undefined reference to `pthread_create’
collect2: ld returned 1 exit status”
i am usingg gcc compile.
plz suggest me
have you use gcc -lpthread of -thread…
I just would like to thank you : your tutorials are very good.
Continue !
nice explanation. Thanks!
Very well written for a beginner like me – a nice introduction to socket programming which I have been looking for. Appreciate it!
dear friends,
i need C++ code for sending/receiving TCP and UDP packets on client and server side…code should send packets at different payload sizes,at different time intervals and check the data rate,packet loss and most important one way delay periodically using both the TCP and UDP in linux ubantu while keeping 3G network/device…
you can mail me for further information
Hi, i need a little help.
I compiled the code for connection to another computer in internal network.
Then i set the firewall on the destination computer: iptables -A INPUT -p tcp –destination-port 80 -m iprange –src-range 192.168.xxx.xxx-192.168.xxx.xxx -j ACCEPT …but the result is always a connection error. What’s wrong? Sorry for bad english.
THank you very much. The style of yours for writing the tutorial is very nice.
Hello Mr. Moon. First of all, I should say that you have expalined the socket programminf step by step in the way of understandable and clear. Thank you so much for that.
However, i have a problem about listen() function. The listen(socket_desc , 3) function hasn’t restricted the telnet termianl numbers with 3. More than 3 telnet terminals can open and the server accepts all of them. But, this function restricts the number of accepting clients with 3. How to deal with it? Can you help me?
sir, can u help me to implement myself an application using socket programming in c? i’m an m.tech student in computer networks, i’ve not implemented anything practically till nw n my professor told me to do an project on application implementaion using socket programming in c. so could u pls help me…
Can you please tell about accept command in Socket?? It actually stuck there until any client connects…I basically wanted to wait let say 10sec…if program executes and no client get connect between 10sec then the accept command will terminate…meanwhile if between 10sec more than one client connects it will accept and will display that I got connection…so please tell about this how can we terminate accept command after certain time…Thanks…Please help
You can try the following options :
1. Use non-blocking socket and accept in a loop for 10 seconds. It would not block and return immediately. After 10 seconds exit the loop.
2. On linux use signals to interrupt the accept call (close the socket and accept should return with an error).
Thank you for the instant help. :) great work i must say.
Dear Binary Tide Team,
I want to ask that is there any script in C-Language through which we can determine the workload of the client connected to the server…I mean can we integrate that script in socket programming? is there any script? Please reply me. I will be very thankful. If you have that script please post it here…Thanks
use `perror` instead of `puts` as an error message.
you’ll get a detailed error.
When i use
free(socket_desc);
it gives segmentation fault (core dumped)
is there any way out?
why would you do free(socket_desc) ?
use the close function
close(socket_desc);
close(socket_desc);
this does not work. That is when i run the program once and the program terminates, the next time i run the server then it is unable to bind. and free seems to work but with that error displayed every time it is run.
you are unable to bind next time, because the socket might already be in use.
print the error number and error message that occurs on doing bind.
to fix this, change the port number and bind should work.
free is used to deallocate memory, not to close sockets.
A cleaner way to do it would be setting the SO_REUSEADDR socket option to make the port reusable after the server terminates, so adding the following code before you bind to the port should solve your problem.
int i=1;
if(setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, (void* )&i, (socklen_t)(sizeof(int)))<0){
printf("ERROR");
}
Hi,How to add two ip addresses to a board having one ethernet port and another one is wifi. means board should connect with through ethernet port & wifi also.
Great tutorial, helped me so much!
I just have a question: why malloc(1)? I’m on 64-bit Ubuntu 12.04 and an int* is 8 bytes. I compiled it and it works but I have no idea why.
Great article, it helps me to understand how to thread connection.
One correction:
new_sock = malloc(1);
new_sock is declared as *int but you are allocating space for 1 byte (on my system is 4 bytes), I thing it must be malloc(sizeof(*new_sock)) or sizeof(int)
oops, I thinK
+1, strikes the eye
Thank you very much.It helped me a lot!
thank you very much. very nice article.
Awesome tutorial for the beginner like me. Please send me some of the socket programming tasks/ problems / real time scenarios where sockets are extensively used. It would be helpful for going deeper into the socket programming.
Thanks!!!
nice explaination for networking programming in C, good stuff.
http://mindregal.com/networkprog.php
can you please explain this:
SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket.
Sockets can be of many types, like TCP, UDP, ICMP. Each of these are a different set of protocols which define the header structure etc.
When creating a function using the socket function like this
socket(AF_INET , SOCK_STREAM , 0);
The 2nd paramter SOCK_STREAM indicates that we want to create a TCP type socket.
TCP sockets are connection oriented and use the send, recv function to send and receive data respectively.
Instead of SOCK_STREAM if we put int SOCK_DGRAM we would create a UDP socket, which does not have the concept of connections. And it uses the sendto/recvfrom functions to send and receive data respectively.
Check out this tutorial on udp socket programming for more
https://www.binarytides.com/server-and-client-programming-with-udp-sockets-in-c-on-linux/
Thanks!!!
the connection handler exit condtion is :
if(read_size == 0)
when this will happen? what will be the trigger for == 0
what about timeout? dosnt tcp connection has timeout?
The recv function returns 0 when the connection has been closed by the peer.
According to the docs
“If no messages are available to be received and the peer has performed an orderly shutdown, recv() shall return 0”
Yes, recv does have a timeout which varies from 15 seconds to 60 seconds or more. So if something does not come in for long it will timeout.
The code shown in the tutorial is just an example and needs a lot of changes before it can be used in a real application.
Is it possible to handle more than 5000 client to running a single IP and single port
A single machine server can handle hundreds of connections.
But it depends on what kind of server it is, how much cpu/ram it consumes to process a single request etc.
I have recent version off gcc (4.4.4) installed in my ubuntu 10.04…but when the program get compiles it compiles through gcc (4.4.3) version…should this happen?
the program has to be compiled like this
hpgc@hpgc:~$ gcc -o tcpnew tcpnew.c -lpthread
note the lpthread, its for linking the pthread library.
Hey! This article was really helpful. I just need to know how can I transfer .txt file via Socket Programming. Please help me. Do you have any link for that??? Also how can I break any txt file in parts. Please help…
for transferring a file, it has to be broken down into parts and each part has to be send
over through socket send function. On the other side the parts have to be combined to produce the original file.
Hey! thanks for your instant reply. I wanted to know How should I break file in parts? Is there any command or function for that??? Can you provide any link that would be helpful for me. Thanks in advance…
hi, i just gave an idea about how it can be done.
for example open a file and read 100 characters and send them over the socket connection.
this can be done using file functions like fopen, fread etc.
do this in a loop till the file has no more characters left.
then on the other side of the connection, the program has to collect all characters in a variable
and save them.
great article ,thank you
tell me how to connect to two pc’s?
what kind of connection do you need ?
For transferring files, use an ftp server program one one machine and an ftp client like a browser on another machine.
hi please let me know how to use ftp for sending file from client to server as a whole file.help and answer will be appreciated
you need to use a ftp client library for doing that.
thanks all of these things
really i need these things and it was amazing to read and check and compile all these
Thanks so so so much…
Hi !
Thank you for the document. It is really very useful and easy to learn.
I am looking forward to learn more about network programming. Please advise me some other source of info.
Thank you.
breaking the file into parts? hmm. that seems difficult.
hello mr.binarytides, do you know how to transfer files (ie. mp3, avi, jpeg, txt, etc) from a client to server, vice-versa using socket programming in C? could you perhaps teach me how? thanks. any help will be appreciated.
File transfer is not straightforward to implement with just sockets.
You need to use a protocol like ftp.
Otherwise you have to build your own technique , for e.g.
break a file in parts and send it from client to server or the otherway , then on the otherside add up all parts
to create the original file. For this you have to use your own custom headers which indicate what part number
of the file is contained in a particular packet etc. It should be a good experiment.