Updated March 23, 2023
Introduction to Socket Programming in C++
Socket programming in C++ is the way of combining or connecting two nodes with each other over a network so that they can communicate easily without losing any data. If we take a real-life example then the socket we see in reality is a medium to connect two devices or systems. It can be either a phone charger plugging into the socket or a USB cable into our laptop. In the same way, Sockets let applications attach to the local network at different ports. Every time a socket is created, the program has to specify the socket type as well as the domain address.
Syntax:
#include <sys/socket.h> // Include this header file for using socket feature in the code
int socket ( int domain, int type, int protocol );
Methods of Socket Programming in C++
A Socket class can be used to create a socket in programming in C++. Methods can be created in many ways. One of the ways is:
public Socket( InetAddress address, int port )
throws IOException
Here is the list of Socket methods that can be used in programming to make code efficient.
1. public InputStream getInputStream()
After creating a socket we need a method to get input from the user in some way. This input stream method will return the InputStream representing the data attached to this socket. It also throws an exception. Make sure the object must be returned every time you call this method to avoid errors.
2. public OutputStream getOutputStream()
After creating a socket we need a method to get output from the user in some way. This output stream method will return the OutputStream representing the data attached to this socket. It also throws an exception. Make sure the object must be returned every time you call this method to avoid errors.
3. public synchronized void close()
Once we create a socket we need to close it also because we can’t leave it open. Therefore, after creating a socket we need a method to close the socket in code once the work is done. This close method will close the socket representing the data attached for security purposes.
A small process we need to follow for socket creation and proceeding further. Below are the mentioned steps you need to follow for Socket programming in C++.
- Create the socket by providing domain, type, and protocol.
- We can use Setsockopted if we need to reuse the address and port. It is optional.
- Once the socket is created Bind method is used to bind the socket to the address and the port number specified in the custom data structure.
- The listen method is used to keep socket inactive when it waits for the client-server connection to establish.
- Accept method will have the very first connection request on the pending connection list in the socket. As it will create a new socket that is already connected and return a new file descriptor. This is the point of contact between server and client where your socket is ready for transferring data.
Examples of Socket Programming in C++
As socket has usually two sides one is the client and another is the server. Let’s discuss both of them in detail.
Example #1 – Socket Client
Following is a C++ program to demonstrate socket programming on the client side.
Code:
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8080
int main ( int argument, char const *argv[] )
{
int obj_socket = 0, reader;
struct sockaddr_in serv_addr;
char *message = "A message from Client !";
char buffer[1024] = {0};
if (( obj_socket = socket (AF_INET, SOCK_STREAM, 0 )) < 0)
{
printf ( "Socket creation error !" );
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Converting IPv4 and IPv6 addresses from text to binary form
if(inet_pton ( AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf ( "\nInvalid address ! This IP Address is not supported !\n" );
return -1;
}
if ( connect( obj_socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr )) < 0)
{
Printf ( "Connection Failed : Can't establish a connection over this socket !" );
return -1;
}
send ( obj_socket , message , strlen(message) , 0 );
printf ( "\nClient : Message has been sent !\n" );
reader = read ( obj_socket, buffer, 1024 );
printf ( "%s\n",buffer );
return 0;
}
Output:
Example #2 – Socket Server
Following is a C++ program to demonstrate socket programming on the server side.
Code:
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#define PORT 8080
int main ( int argument, char const *argv[] )
{
int obj_server, sock, reader;
struct sockaddr_in address;
int opted = 1;
int address_length = sizeof(address);
char buffer[1024] = {0};
char *message = "A message from server !";
if (( obj_server = socket ( AF_INET, SOCK_STREAM, 0)) == 0)
{
pserror ( "Opening of Socket Failed !");
exit ( EXIT_FAILURE);
}
if ( setsockopted(obj_server, SOL_SOCKET, SO_REUSEADDR,
&opted, sizeof ( opted )))
{
pserror ( "Can't set the socket" );
exit ( EXIT_FAILURE );
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
if (bind(obj_server, ( struct sockaddr * )&address,
sizeof(address))<0)
{
pserror ( "Binding of socket failed !" );
exit(EXIT_FAILURE);
}
if (listen ( obj_server, 3) < 0)
{
pserror ( "Can't listen from the server !");
exit(EXIT_FAILURE);
}
if ((sock = accept(obj_server, (struct sockaddr *)&address, (socklen_t*)&address_length)) < 0)
{
pserror("Accept");
exit(EXIT_FAILURE);
}
reader = read(sock, buffer, 1024);
printf("%s\n", buffer);
send(sock , message, strlen(message) , 0 );
printf("Server : Message has been sent ! \n");
return 0;
}
Output:
Conclusion
Socket programming in C++ programming language is generally used to initiate and maintain a communication network between processes residing on different systems. As they allow easy access to the centralized data distributed over other machines. As it causes low network traffic, therefore, it is used for general communications.
Recommended Articles
This is a guide to Socket Programming in C++. Here we discuss the basic concept and various methods of socket programming in C++ with examples and code implementation. You may also look at the following articles to learn more –