Socket Programming in C++
Last Updated :
10 May, 2025
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 provide reliability and connection-based communication, ensuring that data is sent and received in the correct order, without loss or duplication.
- Datagram Sockets: Datagram sockets are used for connectionless, unreliable communication. These sockets are faster but does not guarantee reliable delivery of data.
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 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 clarify
8 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.Features of C++Why
5 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
java.net.Socket Class in Java The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class h
5 min read
Sockets | Python What is socket? Sockets act as bidirectional communications channel where they are endpoints of it.sockets may communicate within the process, between different process and also process on different places.Socket Module- s.socket.socket(socket_family, socket_type, protocol=0) socket_family-AF_UNIX
3 min read
Legacy Socket API in Java The Java Socket API has been around for more than two decades. It has been maintained and updated over that period, but even the most well-kept code ultimately has to be upgraded to stay up with contemporary technologies. The fundamental classes that handle Socket interaction in Java 13 have been re
4 min read
Output of C++ programs | Set 34 (File Handling) What task does the following program perform? CPP #include<iostream> #include<fstream> using namespace std; int main() { ofstream ofile; ofile.open ("text.txt"); ofile << "geeksforgeeks" << endl; cout << "Data written to file" << endl
3 min read