Socket Programming in C++
Last Updated :
13 Aug, 2024
In C++, socket programming refers to the method of communication between two sockets on the network using a C++ program. We use the socket API to create a connection between the two programs running on the network, one of which receives the data by listening to the particular address port, and the other sends the data. One of the features of the socket programming is that it allows the bidirectional communication between the nodes.
In this article, we will create some simple C++ programs to demonstrate the use of socket programming.
What are Sockets?
Sockets can be viewed as the endpoint of the two-way communication between the two programming in the network. They are generally hosted on different application ports and allow bidirectional data transfer.
Types of Sockets
There are two main types of sockets:
- Stream Sockets: Stream sockets (like TCP) are like making a reliable phone call, ensuring that all information is delivered correctly.
- Datagram Sockets: Datagram sockets (like UDP) are more like sending letters. they're faster but might get lost.
Server Stages
1. Creating the Server Socket
We create socket by using the socket() system call. It is defined inside the <sys/socket.h> header file.
Syntax
int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
here,
- Â socketfd: It is the file descriptor for the socket.
- AF_INET: It specifies the IPv4 protocol family.
- SOCK_STREAM: It defines that the TCP type socket.
2. Defining Server Address
We then define the server address using the following set of statements
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(8080);
serverAddress.sin_addr.s_addr = INADDR_ANY;
here,
- sockaddr_in: It is the data type that is used to store the address of the socket.
- htons(): This function is used to convert the unsigned int from machine byte order to network byte order.
- INADDR_ANY: It is used when we don't want to bind our socket to any particular IP and instead make it listen to all the available IPs.
3. Binding the Server Socket
Then we bind the socket using the bind() call as shown.
bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
4. Listening for Connections
We then tell the application to listen to the socket referred by the serverSocket.
listen(serverSocket, 5);
5. Accepting a Client Connection
The accept() call is used to accept the connection request that is recieved on the socket the application was listening to.
int clientSocket = accept(serverSocket, nullptr, nullptr);
6. Receiving Data from the Client
Then we start receiving the data from the client. We can specify the required buffer size so that it has enough space to receive the data sent the the client. The example of this is shown below.
char buffer[1024] = {0};
recv(clientSocket, buffer, sizeof(buffer), 0);
cout << "Message from client: " << buffer << endl;
7. Closing the Server Socket
We close the socket using the close() call and the associated socket descriptor.
close(serverSocket);
Client Stages
Similar to server, we also have to create a socket and specify the address. But instead of accepting request, we send the connection request when we can to sent the data using connect() call.
Then we sent the data using send() call. After all the operations are done, we close the connection using close() call.
1. Creating the Client Socket
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
2. Defining Server Address
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(8080);
serverAddress.sin_addr.s_addr = INADDR_ANY;
3. Connecting to the Server
connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
4. Sending Data to the Server
const char* message = "Hello, server!";
send(clientSocket, message, strlen(message), 0);
5. Closing the Client Socket
close(clientSocket);
Example of Socket Programming in C++
server.cpp
C++
// C++ program to show the example of server application in
// socket programming
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
using namespace std;
int main()
{
// creating socket
int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
// specifying the address
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(8080);
serverAddress.sin_addr.s_addr = INADDR_ANY;
// binding socket.
bind(serverSocket, (struct sockaddr*)&serverAddress,
sizeof(serverAddress));
// listening to the assigned socket
listen(serverSocket, 5);
// accepting connection request
int clientSocket
= accept(serverSocket, nullptr, nullptr);
// recieving data
char buffer[1024] = { 0 };
recv(clientSocket, buffer, sizeof(buffer), 0);
cout << "Message from client: " << buffer
<< endl;
// closing the socket.
close(serverSocket);
return 0;
}
client.cpp
C++
// C++ program to illustrate the client application in the
// socket programming
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
int main()
{
// creating socket
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
// specifying address
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(8080);
serverAddress.sin_addr.s_addr = INADDR_ANY;
// sending connection request
connect(clientSocket, (struct sockaddr*)&serverAddress,
sizeof(serverAddress));
// sending data
const char* message = "Hello, server!";
send(clientSocket, message, strlen(message), 0);
// closing socket
close(clientSocket);
return 0;
}
By compiling and running server and client source files, we get the following output.
Output

As we can see, the message we sent to the server at port 8080 is revived and printed by the server. We can also create a loop where we can keep sending the messages to the server.
Application and Benefits
Real-world Applications
Socket programming finds applications in a myriad of scenarios, from fundamental client-server interactions to intricate distributed systems. Its versatility powers web servers, chat applications, file transfer protocols and online gaming platforms.
Advantages of Socket Programming
Talking in Different Languages: Sockets help programs written in different languages understand each other.
Fast and Efficient Communication: They enable direct communication, making data exchange quicker.
Handling Many Users: Sockets let applications handle many users at the same time, like a busy chat room.
Similar Reads
Socket Programming in C
Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the serv
8 min read
Socket Programming in Java
Socket programming in Java allows different programs to communicate with each other over a network, whether they are running on the same machine or different ones. This article describes a very basic one-way Client and Server setup, where a Client connects, sends messages to the server and the serve
6 min read
Perl | Socket Programming
Socket programming in Perl is a way of connecting two nodes on a network to communicate with each other. Basically, it is a one-way Client and Server setup where a Client connects, sends messages to the server and the server shows them using socket connection. One socket (node) listens on a particul
4 min read
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides: Hands-on application of different programming concepts.Similar syntax to
5 min read
std::promise in C++
In C++ multithreading, a thread is the basic unit that can be executed within a process and to communicate two or more threads with each other, std::promise in conjunction with std::future can be used. In this article, we will discuss the std::promise in C++ and how to use it in our program. What is
3 min read
C++ Programming Basics
C++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before explaining the basics of C++, we would like to clarif
9 min read
C++ Tutorial | Learn C++ Programming
C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc. Why Learn C++?C++
5 min read
10 C++ Programming Tricks That You Should Know
C++ Programming Language is a powerful, versatile, and compiled language, which means the source code is converted into machine language before the execution. In order to make your code as efficient and effective as possible, you should be aware of the following tricks and techniques. Hence, it's be
10 min read
Creating Unix Sockets
Sockets are a means to allow communication between two different processes over the same or different machines/networks. To be more precise, it's a way to talk to other computers and exchange data. In Unix, every I/O action is done by writing or reading a file descriptor. Sockets are the end point o
8 min read
Introduction to C++ Programming Language
C++ is a general-purpose programming language that was developed by Bjarne Stroustrup as an enhancement of the C language to add object-oriented paradigm. It is a high-level programming language that was first released in 1985 and since then has become the foundation of many modern technologies like
4 min read