What are the Methods of Socket Programming in C++?

Do you know what socket programming in C++ is? Would you like to know about the methods of socket programming in Cpp? Well then, let’s gain some knowledge about Socket programming!

Sockets are a tool to establish real-time communication between two nodes in a network. It is used in various modern applications like chat apps to get real-time data.

We can use sockets in C++ to facilitate communications in our C++ apps. In this article, we will learn about the methods you can use in C++ to add sockets to our project. So, let’s get started!

Summary Of The Article:

  • Socket programming helps us establish basic internet data communications using various protocols and IPs.

  • A socket API forms an endpoint of a two-way network connection in a client-server network model.

  • Sockets are of mainly two types – Stream sockets (use TCP) and datagram sockets (use UDP).

  • Datagram sockets are less reliable than stream sockets.

What are the Two Main Types of Sockets?

Sockets are the endpoints of a network connection between two nodes. They facilitate network communication and data exchange between nodes in a client-server model. There are two main types of sockets. These are-

  • Stream sockets: These sockets form a reliable connection between two nodes that is connection-oriented. Example of this socket type is the TCP sockets. Stream sockets exchange data in continuous stream making sure that it is successfully transmitted.

  • Datagram sockets: These sockets provide connectionless communication over the network. For instance UDP(User datagram protocol) sockets. Datagram sockets are faster but less reliable than stream sockets.

Let’s study what is the process and steps involved in socket programming. Keep reading to know more.

What Is The Process Of Socket Programming? Read Below

Let’s get to know the process of how sockets establish connections between devices. Here, is the list of steps that undergo during the process. Have a look at them so that you can easily understand the methods and their purpose.

  1. At first, an endpoint or node is created on both sides for making the communication.

  2. Then an IP address is assigned to both of the nodes. This helps to distinguish them from the rest of the network.

  3. Here, one node will start making a connection with the other one.

  4. The other node will then accept the connection request.

  5. Then the nodes will exchange some data.

  6. At last, when the process is completed, both endpoints will get dissolved.

Ways To Perform Socket Programming Using C++

Now, after clearing the basics of Socket programming, it is time to move forward. Here, we will discuss some ways in C++ programming language that allow us to perform socket operations. Let us know about them, one by one briefly.

  • InputStream Method: After creating one socket, we need to take some inputs from the user. The InputStream method will help us in this case. This will take the inputs from the user. Then it uses it inside of the socket. After that, it returns the data that is attached to the socket.

  • OutputStream Method: Now, after providing the input to the socket, it is also important to bring back the output from the socket. It will provide the output from the socket using the output stream.

  • Synchronized Method: This is the method that helps to close the socket. After creating the socket, it will be good practice to close the socket after being used. This will help to close the socket which is opened in the code.

What Are The Methods Of Socket Programming In C++?

Like every programming language, socket programming also has some unique functions for fulfilling the operations. All these functions are inbuilt and we also refer to them as methods. So, we have to only use them properly. We don’t need to define the functions broadly. 

Let us know of the functions one by one briefly. Have a look at them below!

-> Server Side Functions

There are some in-built and essential functions provided by C++ for socket programming. Let us get to know about them one by one. We will first start with functions that are implemented for the server.

Socket()

This is the method that is being used for implementing the endpoints of the program. By using this function, we can able to make two nodes. One is the client socket and the other is the server socket.

Syntax:

				
					int socketname = socket(domain, type, protocol);
				
			

Bind()

This function is a system call that assigns a specific local address and a port number in a custom data structure to the nodes so that communication is possible. Bind() allows the socket to listen to the requests.

Syntax:

				
					bind(socketfd, const struct sockaddr *addr, socklen_t addrlen);
				
			

Here, socket fd is the socket file descriptor, ‘addr’ is the point to ‘sockaddr’ which contains the IP (Internet Protocol) address and TCP port number.

Listen()

This system call puts the socket in listening mode and gets it to respond to the client’s request. It has two parameters – one is the socket file descriptor and the other is the backlog parameter that represents the maximum number of pending connections in the queue.

Syntax:

				
					listen(sockfd, backlog);
				
			

Accept()

This system call helps to initiate the communication from the server side by accepting a new connection request from the client socket. The first connection request is extracted from the queue of pending connections and a new connected socket is created.

Syntax:

				
					int new_socket = accept(server_fd, (struct sockaddr *)&client_address, &addr_len);
				
			

Here, server_fd is the listening socket file descriptor. The function returns a new socket file descriptor referring to the connection. If there is an error connecting, it returns -1.

-> Client-Side Functions

Here, we are talking about a client-server network. Thus, it is only reasonable for the client node to have its own socket and some functions of its own to establish a socket connection with the server socket. So, let us see some methods that the client uses to establish communication with the server.

Connect()

This function is a system call that initiates the connection request from the client socket’s end. It takes all the parameters like the file descriptor, a pointer to the structure storing the server’s address, and the size of the address structure. The syntax for it is given below.

Syntax:

				
					connect(client_fd, (struct sockaddr *)&server_address, sizeof(server_address)
				
			

Send() or Recv()

These are the functions by which both nodes can exchange data over the network. The send system call sends the data to the connected socket while recv() system call is used to retrieve the data from the connected socket (server socket).

Syntax:

				
					// for send()
send(new_socket, message, strlen(message), 0);
// 0 depicts the socket will choose its default protocol
// for recv()
int bytes_received = recv(new_socket, buffer, sizeof(buffer), 0);
				
			

Close()

This function is used to make the connected socket close to prevent data leaks.

Syntax:

				
					close(socketname); 
				
			

Implementation Of Socket Programming In C++:

Here, we need the socket with the help of the Socket function by providing the arguments like domain, type & protocol. Then we can use the Setsockopted function. This will need to reuse the internet address & the port again.

After that, we need to use the Bind() function. This will help to assign a new address to the socket. As it works on the Client-Server method. There will be Listen() method is being used. Then we have to use the Accept() method to make the connection request.

Then the Send() or Recv() function is used for exchanging the data between two nodes. After making all those operations, it is now time to close the nodes. The Close() method will be used to end the nodes after being used.

Socket programming is a server-client method. so we have to develop both in the C++ programming language. It is important to have the essential header files imported into your code.

Client-Side Code:

				
					#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

#define PORT 8081

int main ( int argument, char const *argv[] ){

    int obj_socket = 0, reader;
    struct sockaddr_in serv_addr;

     char *message = "Message From Client";
    char buffer[1024] = {0};

    if (( obj_socket = socket (AF_INET, SOCK_STREAM, 0 )) < 0){
	// print the socket creation error if there is error opening socket
        printf ( "Socket Creation Error !" ); 
	return -1;
	}
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(PORT);
    // Converting IPv4 and IPv6 address structure from text to binary form

    if(inet_pton ( AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0){

    printf ( "\nInvalid address!\n" );
    return -1;
        
    }
    
    if ( connect( obj_socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr )) < 0){
    printf ("Connection Failed" );
    return -1;
        
    }
    send ( obj_socket , message , strlen(message) , 0 );
    printf ( "\nClient : Message Sent\n" );
    reader = read ( obj_socket, buffer, 1024 );
    printf ( "%s\n",buffer );
    return 0;
}
				
			

To establish a socket connection, we have to write the code for both client-side and the server. The above sample client code follows the given steps:

  • All necessary header files are added. Each header file is responsible for the operating system call or in-built methods and functions.

  • The client connects to the server socket on port number 8081.

  • A new socket of the stream socket type is created which is represented with the new file descriptor (obj_socket)

  • The server address is designed of the IPv4 address family and the port number is then converted to network byte order.

  • The connect() method system call is used to establish a socket connection and sends a connection request to the server with the data.

  • A confirmation message is received when the server responds back with the data.

Let us see the output of the above code. This will help to understand better.

Output:

Client-Side Code Output

Real-World Applications Of Socket Programming

Let’s get to know some real-world use cases and applications of using sockets. This concept is widely used whenever we need to perform data exchange operations.

Below are some of the applications for using socket programming. Have a look to learn more!

  • In web servers and browsers

Sockets can be used in a web server to handle the HTTP/HTTPS requests and form a connection between the browser and the web pages. The incoming connection requests are listened to by the server and it responds to those requests.

  • Chat applications

Chat rooms and real-time chat apps use sockets to exchange messages between users. The users can communicate in a chat room with a lot of people or privately with one individual.

  • Multiplayer Gaming

If you love computer games and like to connect with your friends for a game, you have sockets to thank. In online gaming platforms, UDP sockets are used for data exchange or messaging quickly for connectionless communication so that players can interact in real-time.

These games also use TCP sockets for critical processes, such as results or in-game purchases. Games like Fortnite use a combination of both of these sockets.

  • File Transfer Protocol

Another use of sockets is in web protocols like a file transmission control protocol to transfer data and files over a network. In FTP, the server socket listens to the client’s request for file transfer and responds to it.

  • Video and Audio Streaming

Sockets are also used by online streaming platforms like YouTube, Netflix, etc for media transmission. These platforms use UDP sockets for low-latency streaming and TCP to handle metadata and control commands like playback.

Conclusion:

As we saw Socket programming in C++ is a very important topic.

We should clear the basics of the programming language & the Data Structures. Also, we need to have a minimum knowledge of the IP, and TCP models in a proper way.

So, hope you have liked this piece of article. Share your thoughts in the comments section and let us know if we can improve more.

Domycodinghomework also offers a wide range of programming and coding help services for you to benefit from. Don’t miss out! Visit https://domycodinghomework.com/ and our expert team will be there to help you out.

Takeaways:

  • Socket programming works on a server and client network topology and helps us to establish a communication channel between two endpoints.

  • The client sends a request to the server and the server interprets the incoming connection request and accepts it.

  • Sockets use stream-oriented protocol and datagram protocol for communication.

Leave a Comment

Your email address will not be published. Required fields are marked *