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

Do you know what is Socket programming in C++? Have you ever thought what is the necessity of Socket programming in C++? Let us gain some knowledge about Socket programming in C++.

But before we start a discussion on the topic, let us first know about Socket programming by analyzing one real-life problem.

Suppose, you can’t make a call with your friend. But this is not as easy as we expect. Let us think about the process from the beginning.

If you want to make a call to your friend, you need to first buy a mobile. Or you have to bring one landline phone to your house. The same thing has to be done by your friend also. He also needs to buy a phone. Then after buying the phone you need to take a sim card. Or in the case of a landline, you need to bring the connection. The same thing goes for your friend also.

Now, after all of this, you dialed your friend’s phone number. The phone will ring at the other end. Your friend then receives the call. You both will share some data. Then both of you will hang up the phone call.

Now, you might think what is the connection between Socket programming in C++ & making a phone call? You will get the answer at the very right time when we will start a discussion on the method of Socket programming.

For now, we can say that Socket programming in C++ works same as the making a phone call to a friend. This is as simple as making a phone call. But before we jump-start the implementation of Socket programming, let us know what is socket programming in C.

 

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

 

 

 

What Is Socket Programming In C/C++?

 

Socket programming C helps to communicate between two nodes or between two devices. When you are calling your friend, some processes are going on in the background. Can we see those processes? Socket programming is the same as telephonic conversation. In Socket programming C, a node will transfer some data to the other node. The other node will decode the message & performs some operation. This is the simple definition of Socket programming in C++.

We can take the example of Google Chrome. We can assume as Google Chrome is one node (client). It requests the proper node to get some information from it. The other node is the server. It takes some necessary information from the server & prints them on the computer screen. This is the way the Socket programming in C++ works.

 

 

What are the Steps Of Socket Programming In C++? Read Below

 

Here, we will make a list of steps. These steps will help you to understand each & every process in the Socket programming in C++. Let us see those processes one by one.

  1. At first, an endpoint or node is created on both sides for making the communication. This is the step where we buy mobile phones for making telephone communication.
  2. Then an IP address is assigned to both of the nodes. This helps to distinguish them from the rest of the network. This is the step where we buy the sim cards for calling purposes.
  3. Here, one node will start making a connection with the other one. This is the step where you are making a phone call to your friend.
  4. The other node will then accept the connection request. This is the step where your friend receives your call.
  5. Then the nodes will make some data exchanges. Like you & your friend will talk over the telephone.
  6. At last, when the process is completed, both endpoints will get dissolved. Like both of you hung up your phone as you talked with each other.

 

What are the Important Functions Of Socket Programming In C++?

 

There are some important functions in socket programming. Like in every programming language, socket programming is also having some unique functions for fulfilling the operations. All these functions are inbuilt. 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.

  • Socket() Function: 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 for the client. And another is for the server.
  • Bind() Function: This is the function that helps to assign a unique address to both nodes. In this way, they can communicate with each other over the internet.
  • Connect() Function: This is the function that initiates the connection. It is like dialing the number on mobile.
  • Listen() Function: This is mainly on the server side to respond to the client’s request.
  • Accept() Function: This is also a server-side function. This helps to initiate the communication from the server side also.
  • Send() or Recv() Functions: These are the functions by which both nodes can exchange data over the network.
  • Close() Function: This function helps to close the nodes that have opened first.

 

Methods Of Socket Programming In C++:

 

Now, after clearing the basics of Socket programming in C++, it is time to move forward. Here, we will discuss some methods in C++ programming languages that help to make some operations on the socket. 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 outputstream.
  • 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.

 

Implementation Of Socket Programming In C++:

 

Here, first, we need to 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 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() methods will use 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.

 

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){

                        printf ( "Socket 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!\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;}

 

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

 

Output:

Client Side Code Output

 

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 8081

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 ( "Socket Failed"); exit ( EXIT_FAILURE);}

              if ( setsockopted(obj_server, SOL_SOCKET, SO_REUSEADDR, &opted, sizeof ( opted ))){

                             pserror ( "Socket Can't Set" );  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 Get From 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 Sent\n");

              return 0;}

 

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

 

Output:

Server Side Code Output

 

Conclusion:

 

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

What is socket programming in C is a very important subtopic to consider. We need to clear socket programming C in a good manner.

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 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.

Leave a Comment

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