Reader small image

You're reading from  Expert C++ - Second Edition

Product typeBook
Published inAug 2023
PublisherPackt
ISBN-139781804617830
Edition2nd Edition
Right arrow
Authors (5):
Marcelo Guerra Hahn
Marcelo Guerra Hahn
author image
Marcelo Guerra Hahn

Marcelo Guerra Hahn, With over 18 years of experience in software development and data analysis, Marcelo Guerra Hahn is a seasoned expert in C++, C#, and Azure. As an Engineering Manager at Microsoft C++ Team and former leader of SoundCommerce's engineering team, Marcelo's passion for data and informed decision-making shines through. He shares his knowledge as a lecturer at esteemed institutions like Lake Washington Institute of Technology and University of Washington. Through this book, Marcelo aims to empower readers with advanced C++ techniques, honed by real-world experience, to become proficient programmers and skilled data analysts.
Read more about Marcelo Guerra Hahn

Araks Tigranyan
Araks Tigranyan
author image
Araks Tigranyan

Araks Tigranyan is a passionate software engineer at Critical Techworks, with an unwavering love for the world of programming, particularly in C++. Her dedication to crafting efficient and innovative solutions reflects her genuine passion for coding. Committed to excellence and driven by curiosity, Araks continuously explores new technologies, going above and beyond to deliver exceptional work. Beyond programming, Araks finds solace in sports, with football holding a special place in her heart. As an author, Araks aspires to share her profound expertise in C++ and inspire readers to embark on their programming journeys.
Read more about Araks Tigranyan

John Asatryan
John Asatryan
author image
John Asatryan

John Asatryan, the Head of Code Republic Lab at Picsart Academy, seamlessly blends his academic background in International Economic Relations from the Armenian State University of Economics with his ventures in technology and education. Driven by a genuine passion for coding, John's commitment to empowering aspiring developers is evident in his expertise in the field. His unwavering dedication to bridging the gap between education and technology inspires others to pursue their coding dreams.
Read more about John Asatryan

Vardan Grigoryan
Vardan Grigoryan
author image
Vardan Grigoryan

Vardan Grigoryan is a senior backend engineer and C++ developer with more than 9 years of experience. Vardan started his career as a C++ developer and then moved to the world of server-side backend development. While being involved in designing scalable backend architectures, he always tries to incorporate the use of C++ in critical sections that require the fastest execution time. Vardan loves tackling computer systems and program structures on a deeper level. He believes that true excellence in programming can be achieved by means of a detailed analysis of existing solutions and by designing complex systems.
Read more about Vardan Grigoryan

Shunguang Wu
Shunguang Wu
author image
Shunguang Wu

Shunguang Wu is a senior professional staff at Johns Hopkins University Applied Physics Laboratory, and received his PhDs in theoretical physics and electrical engineering from Northwestern University (China) and Wright State University (USA), respectively. He published about 50 reviewed journal papers in the area of nonlinear dynamics, statistical signal processing and computer vision in his early career. His professional C++ experience started with teaching undergraduate courses in the late 1990s. Since then he has been designing and developing lots of R&D and end-user application software using C++ in world-class academic and industrial laboratories. These projects span both the Windows and Linux platforms.
Read more about Shunguang Wu

View More author details
Right arrow

Networking and Security

Network programming continues to become more and more popular. Most computers are connected to the internet, and more and more applications now rely on being connected. From simple program updates that might require an internet connection to applications that depend on a stable internet connection, network programming is necessary for application development.

Designing a network application is an excellent addition to your skillset as a programmer. This chapter will discuss the standard networking extension and see what is needed to implement networking-supported programs. We will focus on the main principles of networking and the protocols driving communication between devices.

Once an application uses a network, one of the significant challenges developers face is keeping the application secure. Whether it’s related to the input data being processed or coding with proven patterns and practices, the application’s security must be the top...

Technical requirements

The g++ compiler with the -std=c++2a option is used to compile the examples in this chapter. You can find the source files used in this chapter at the following GitHub repository: https://github.com/PacktPublishing/Expert-C-2nd-edition/tree/main/Chapter13

Introduction to networks, the OSI model, and network programming using sockets

Two or more computers can interact using networks. For example, computers connect to the internet using a hardware component called a network adapter or a network interface controller (NIC). The operating system installed on the computer provides drivers to work with the network adapter—that is, to support network communications. The computer must have a network adapter installed with an OS that supports the networking stack.

By stack, we mean the layers of modifications the data goes through when traveling from one computer to another. For example, opening a website on a browser renders data gathered through the network. That data is received as a sequence of zeros and ones and then transformed into a more intelligible form for the web browser. Layering is essential in networking. Network communication as we know it today consists of several layers conforming to the Open Systems Interconnection...

Understanding network protocols

A network protocol is a collection of rules and data formats that define intercommunication between applications. For example, a web browser and server communicate via HTTP. HTTP is more like a set of rules than a transport protocol. Transport protocols are at the base of every network communication. An example of a transport protocol would be TCP. When we mentioned the TCP/IP suite, we meant the implementation of TCP over IP. We can consider the IP protocol as the heart of internet communications.

It provides host-to-host routing and addressing. Everything we send or receive online is packaged as an IP packet. The following diagram shows what an IPv4 packet looks like. In this context, an octet refers to a group of 8 bits equivalent to 1 byte:

Figure 13.6 – IP packet

Figure 13.6 – IP packet

The IP header weighs 20 bytes. It combines necessary flags and options for delivering a packet from the source address to the destination address...

Designing an echo server

For this example, we will implement an echo server. An echo server is a network server that echoes back any data it receives from a client. In other words, when a client sends a message to an echo server, the server returns the same message to the client. The purpose of an echo server is to demonstrate basic communication between a client and a server. The echo server operates based on a simple request-response model. When a client connects to the server, it establishes a communication channel with the server. The client can then send a message to the server over this channel. The server receives the message, processes it, and sends the same message back to the client. The client can then receive and display the echoed message. Echo servers are commonly used for testing network connectivity, troubleshooting, and verifying the integrity of network communication. They allow developers to check whether the network functions properly by verifying that the data...

Securing applications

Compared to many languages, C++ is a little harder to master regarding secure coding. Plenty of guidelines provide advice regarding how to and how not to avoid security risks in C++ programs. One of the most popular issues discussed in Chapter 1, Building C++ Applications, is using preprocessor macros. The example we used had the following macro:

#define DOUBLE_IT(arg) (arg * arg)

Improper use of this macro leads to logic errors that are hard to spot. In the following code, the programmer expects to get 16 printed to the screen:

int res = DOUBLE_IT(3 + 1);std::cout >> res >> std::endl;

The output is 7. The issue here is with the missing parentheses around the arg parameter; that is, the preceding macro should be rewritten as follows:

#define DOUBLE_IT(arg) ((arg) * (arg))

Although this example is popular, we strongly suggest avoiding macros as much as possible. C++ provides many constructs that can be processed at compile time, such...

Securing network applications

In the previous section of this book, we designed a network application that receives client data using socket connections. Besides the fact that most viruses that penetrate the system are from the outside world, network applications have this natural tendency to open the computer to various threats on the internet. First, an open port exists when running a network application. Someone who knows the same port your application listens to can intrude by faking protocol data. We will mostly discuss the server side of network applications here; however, some topics also apply to client applications.

One of the first things you should do is incorporate client authorization and authentication. These are two terms that are easy to confuse. Be careful not to use them interchangeably; they are different, as detailed here:

  • Authentication is the process of validating client access. This means that not every incoming connection request is served right away...

Summary

In this chapter, we introduced designing network applications in C++. We started by introducing the basics of networking. Understanding networking completely takes a lot of time, but there are several foundational concepts that every programmer must know before implementing an application in any way related to the network. Those foundational concepts include layering in the OSI model and different kinds of transport protocols, such as TCP and UDP. Understanding the differences between TCP and UDP is necessary for any programmer. As we learned, TCP makes reliable connections between sockets, the next thing a programmer encounters when developing network applications. Those are the connection points of two instances of applications. Whenever we need to send or receive data through a network, we should define a socket and work with it almost as usual with a regular file.

All the abstractions and concepts we use in application development are handled by the OS and, in the end...

Questions

  1. List all seven layers of the OSI model.
  2. What’s the point of port numbers?
  3. Why should you use sockets in network applications?
  4. Describe the sequence of operations you should perform on the server side to receive data using a TCP socket.
  5. What are the differences between TCP and UDP?
  6. Why shouldn’t you use macro definitions in your code?
  7. How would you differentiate between different client applications when implementing a server application?

Further reading

For further information, refer to the following resources:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Expert C++ - Second Edition
Published in: Aug 2023Publisher: PacktISBN-13: 9781804617830
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Marcelo Guerra Hahn

Marcelo Guerra Hahn, With over 18 years of experience in software development and data analysis, Marcelo Guerra Hahn is a seasoned expert in C++, C#, and Azure. As an Engineering Manager at Microsoft C++ Team and former leader of SoundCommerce's engineering team, Marcelo's passion for data and informed decision-making shines through. He shares his knowledge as a lecturer at esteemed institutions like Lake Washington Institute of Technology and University of Washington. Through this book, Marcelo aims to empower readers with advanced C++ techniques, honed by real-world experience, to become proficient programmers and skilled data analysts.
Read more about Marcelo Guerra Hahn

author image
Araks Tigranyan

Araks Tigranyan is a passionate software engineer at Critical Techworks, with an unwavering love for the world of programming, particularly in C++. Her dedication to crafting efficient and innovative solutions reflects her genuine passion for coding. Committed to excellence and driven by curiosity, Araks continuously explores new technologies, going above and beyond to deliver exceptional work. Beyond programming, Araks finds solace in sports, with football holding a special place in her heart. As an author, Araks aspires to share her profound expertise in C++ and inspire readers to embark on their programming journeys.
Read more about Araks Tigranyan

author image
John Asatryan

John Asatryan, the Head of Code Republic Lab at Picsart Academy, seamlessly blends his academic background in International Economic Relations from the Armenian State University of Economics with his ventures in technology and education. Driven by a genuine passion for coding, John's commitment to empowering aspiring developers is evident in his expertise in the field. His unwavering dedication to bridging the gap between education and technology inspires others to pursue their coding dreams.
Read more about John Asatryan

author image
Vardan Grigoryan

Vardan Grigoryan is a senior backend engineer and C++ developer with more than 9 years of experience. Vardan started his career as a C++ developer and then moved to the world of server-side backend development. While being involved in designing scalable backend architectures, he always tries to incorporate the use of C++ in critical sections that require the fastest execution time. Vardan loves tackling computer systems and program structures on a deeper level. He believes that true excellence in programming can be achieved by means of a detailed analysis of existing solutions and by designing complex systems.
Read more about Vardan Grigoryan

author image
Shunguang Wu

Shunguang Wu is a senior professional staff at Johns Hopkins University Applied Physics Laboratory, and received his PhDs in theoretical physics and electrical engineering from Northwestern University (China) and Wright State University (USA), respectively. He published about 50 reviewed journal papers in the area of nonlinear dynamics, statistical signal processing and computer vision in his early career. His professional C++ experience started with teaching undergraduate courses in the late 1990s. Since then he has been designing and developing lots of R&D and end-user application software using C++ in world-class academic and industrial laboratories. These projects span both the Windows and Linux platforms.
Read more about Shunguang Wu