Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Asio
3.
Networking Protocols
4.
Transmission Control Protocol (TCP)
4.1.
ip::tcp
5.
User Datagram Protocol (UDP)
5.1.
ip::udp
6.
Internet Control Message Protocol (ICMP)
6.1.
ip::icmp
7.
Implementation of TCP Class
7.1.
Server-Side
7.1.1.
Code 
7.1.2.
Output
7.2.
Client-Side
7.2.1.
Code 
7.2.2.
Output
8.
Frequently Asked Questions
8.1.
What is Asio?
8.2.
What is the need for network protocols?
8.3.
What is the use of the Asio library?
8.4.
What is the difference between TCP, UDP, and ICMP?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

TCP, UDP, and ICMP Networking

Introduction

Hey Ninjas! Hope you all are doing well. Have you ever wondered how the data you transfer to other devices is monitored? It is done with the help of the protocols. In this article, we will discuss the protocols and learn about the TCP, UDP, and ICMP Networking protocols and how you can use them in Asio.

tcp,udp, and icmp networking

Before starting with protocols, we must be aware of Asio, so let’s begin with the introduction of Asio.

Asio

Asio is also known as asynchronous input-output. It is a C++ library specially designed for input, output, and networking. It is open-source and cross-platform. Many platforms support Asio, like Linux, Windows, macOS, etc. It was developed in 2003 by Christopher M. Kohlhoff and was released under Boost Software License. It uses a modern C++ approach to provide the developers with an asynchronous model.

C++ logo

Now let’s begin with our topic and first look at the protocols.

Networking Protocols

The protocols in networking are the set of certain rules used for processing and formatting the data over the internet. The computers use many software and hardware which further use protocols to communicate with each other. 

networking protocols

For example, in any type of operating system, be it Windows, Mac, they are provided with the IP addressing to work with IP protocols.

Let’s learn about the TCP, UDP, and ICMP networking protocols.

Also read, Abstract Data Types in C++ and Application of Oops

Transmission Control Protocol (TCP)

The Transmission Control Protocol (TCP) is a protocol of the Internet protocol suite. It is a reliable protocol. TCP establishes the connection before the communication occurs; hence it is a connection-oriented protocol. It divides the data taken from the application layer into several packets and transmits them after providing them with numbering.

The features of TCP are

🔶 Full duplex communication means that data is transferred in both directions simultaneously.

🔶 TCP is a reliable protocol, i.e., data is transmitted securely without any loss.

🔶 It is a connection-oriented protocol that is it establishes a connection before transferring the data.

🔶 TCP provides flow and error control mechanisms to ensure the reliable transfer of data.

🔶 It takes care of the congestion (amount of traffic in the network).

🔶 The order of data is maintained during the transmission. The receiver will get the data in the same order in which it was transferred.

ip::tcp

Asio provides support for the Internet protocol. We can use TCP in Asio through ip::tcp to maintain the connection and perform different functionalities. It covers the flags which are needed for the TCP, like the Synchronization flag, acknowledgment flag, reset flag, etc. Flags are used to define the state of the connection and indicate additional information.

We need to use the header asio/ip/tcp.hpp and the convenience header asio.hpp to start using the tcp class in Asio.

The flags which are required for the TCP sockets are part of the ip::tcp class. The following are the types of ip::tcp class.

ip::tcp

User Datagram Protocol (UDP)

The User Datagram Protocol (UDP)  forms a part of the process to process communication. It is an alternative to the TCP protocol. It is a connectionless protocol, i.e., it does not require any connection for data transfer. It uses multiple port numbers defined between 0 and 1023. 

The features of UDP are

🔷 UDP is an unreliable protocol. It contains the minimum communication mechanisms and follows best-effort services.

🔷 It does not create a path before sending the data, i.e., it is a connection-less protocol; hence data may get lost. 

🔷 The order of data is not maintained. It does not guarantee the reliable transmission of data.

🔷 There is no acknowledgment of the data sent; hence it is a stateless protocol.

🔷 The transmission speed is high since there is no connection as in TCP.

ip::udp

The functionality of UDP in Asio can be used through the ip::udp class. It is used for the UDP sockets and provides the flags which are needed for UDP.

The requirements for the UDP class are as follows: Header file - asio/ip/udp.hpp and Convenience header - asio.hpp. One needs to include these files in their code to start using UDP.

The types of ip::udp class are shown in the below table:

ip::udp

The member functions of the UDP class are family, protocol, type, v4 (static), and v6 (static).

Internet Control Message Protocol (ICMP)

The Internet Control Message Protocol (ICMP) is a network layer protocol that is primarily used for error handling in network devices like routers. It can be used to send control messages to hosts and network devices like routers. ICMP is used to report the errors and debug them. The types of ICMP messages are information, error reporting, and query messages.

The features of ICMP are

🔶 ICMP is used for reporting errors when two devices are connected through the internet are communicating with each other.

🔶 ICMP acts as a diagnostic tool for assessing the network’s performance.

🔶 It can be used to kill the network's performance by using a Smurf attack, ICMP flood, etc., to affect the network functionality.

ip::icmp

The flags that are necessary for ICMP sockets are present in the ip::icmp class. It requires the header file asio/ip/icmp.hpp and the convenience header asio.hpp. The member functions of the ICMP class are family, protocol, type, v4 (static), and v6 (static). 

The types of ip::icmp are the same as that of ip::udp; only the syntax differs. Refer to the following table for the types of ip::icmp with their description and syntax.

ip::icmp

This was all about TCP, UDP, and ICMP. Now let’s see an example to show the use of the ip::tcp class.

Implementation of TCP Class

We have demonstrated the use of ip::tcp class with the help of an example. We have implemented socket programming by running a server-side and a client-side code. A tcp::socket is used to represent an endpoint for sending and receiving data across a computer network. The tcp::endpoint is used to specify the IP address and protocol port that the application wants to listen to. The tcp::acceptor is used to accept the request coming from the client for a new connection. The implementation of both codes is shown below.

Server-Side

First, we need to accept the request using tcp::acceptor. Then we created a socket using tcp::socket. Now we have used a streambuf class that represents a buffer of data to read data as a stream. We are storing the data in a string and displaying it. After reading, we performed a write operation to send the response to the client.

Code 

#include <iostream>
#include <asio.hpp>

using asio::ip::tcp;

int main() {
    asio::io_service io_service;
    // Listen for new connection
    tcp::acceptor acceptor_(io_service, tcp::endpoint(tcp::v4(), 8080));
    //socket creation
    tcp::socket socket_(io_service);
    // Waiting for connection
    acceptor_.accept(socket_);

    // Read operation
    asio::streambuf buf;
    asio::read_until(socket_, buf, "\n");
    std::string message = asio::buffer_cast<const char*>(buf.data());

    std::cout << message << std::endl;

    // Write operation
    const std::string msg = "Hello Ninjas! This message is sent from Server!\n";
    asio::write(socket_, asio::buffer(msg));
    std::cout << "Server has sent a message to the Client!" << std::endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Output

Client-Side

First, we have created a socket using tcp::socket; then, a connection request is made to the server, which is accepted using TCP. We have sent a message to the server using the write operation. In case of an error, we will print the error message. The streambuf is again used to read the response from the server. If there is no error, we will print the message received.

Code 

#include <iostream>
#include <asio.hpp>

using asio::ip::tcp;

int main() {
    asio::io_service io_service;
    tcp::socket socket(io_service);

    // Connect the socket
    socket.connect(tcp::endpoint(asio::ip::address::from_string("127.0.0.1"), 8080));
   
    const std::string msg = "Hello Ninjas! This message is from Client!\n";
    asio::error_code error;
    asio::write(socket, asio::buffer(msg), error);
    if (!error) {
        std::cout << "Client has sent a message to Server!" << std::endl;
    }
    else {
        std::cout << "send failed: " << error.message() << std::endl;
    }

    // Getting response from server
    asio::streambuf receive_buffer;
    asio::read(socket, receive_buffer, asio::transfer_all(), error);
    if (error && error != asio::error::eof) {
        std::cout << "receive failed: " << error.message() << std::endl;
    }
    else {
        const char* data = asio::buffer_cast<const char*>(receive_buffer.data());
        std::cout << data << std::endl;
    }

    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Output

Also read, Difference Between Structure and Union

Frequently Asked Questions

What is Asio?

Asio is a cross-platform, open-source C++ library. It is an underrated C++ library designed for input, output, and networking purposes. Asio stands for asynchronous input-output. Christopher M. Kohlhoff developed Asio in 2003. 

What is the need for network protocols?

The protocols are required to monitor the communication between and within the companies and individuals. It is important to understand the sender first. The protocols provide various levels of security and scalability over large networks.

What is the use of the Asio library?

Asio helps in doing network programming using C++ language. It allows the processing of data asynchronously by providing asynchronous I/O models.

What is the difference between TCP, UDP, and ICMP?

The TCP and UDP protocols are the transport layer protocols, while the ICMP is a network layer protocol. They are required for data transfer, while ICMP is primarily used for error handling, sending, and debugging errors. 

Conclusion

In this article, we discussed protocols and learned about TCP, UDP, and ICMP networking protocols. We have also discussed the syntax and types of these three protocols. You can check out our other articles if you want to dive deep into other concepts related to Asio -

👉 Asio Serial Ports

👉 Asio Files


You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questionsand the Ultimate guide path for interviews. Do upvote our blogs to help other ninjas grow.

Happy Coding !!

Live masterclass