Create a Port Scanner in C++

In this tutorial, we will learn about how to create a simple Port Scanner in C++. Port scanners are programs that attempt connection to the server via the specified ports.

We use the information these programs provide to determine if a port is open or closed.
We use this information to look for vulnerabilities in our network. Often, an open port can compromise the security of our system. Therefore, it is useful to keep track of which ports are open.

Port scanner in C++

We look at a simple implementation of this project in C++. To do this, we require the ‘Simple and Fast Multimedia Library’ (SFML).
The steps to install necessary header files for Visual Studio are given here. Please ensure that you have installed the appropriate libraries for your compiler for the proper working of this program.

Here are a few points to note:

  1. sf::TcpSocket().connect() connects the socket to a remote peer and returns the status code.
  2. Socket functions return codes known as status codes. sf::Socket::Done is a status code. It denotes that the socket has either sent or received data.
  3. If these values are equal for a given port, it implies that the port is open.
#include <iostream>
#include <SFML/Network.hpp>
#include <string>

using namespace std;

bool is_port_open(const std::string& address, int port)
{
    return (sf::TcpSocket().connect(address, port) == sf::Socket::Done);
}

int main()
{
    // we can input any valid address instead of '"localhost"' 
    // we can input any valid port number instead of 80  
    
    if (is_port_open("localhost", 80))
        cout << "OPEN";
    else
        cout << "CLOSED";

    return 0;
}

Sample Output

CLOSED

Of course, it is important to note that we get different outputs (‘OPEN’ or ‘CLOSED’) depending on the current status of the port.
Also, it is important to keep in mind that portscanning websites can be considered hacking in some places. Hence, please replace “localhost” with “scanme.nmap.org” if you wish to test this code with a remote host.

Conclusion

In this tutorial, we learned how to create a simple port scanner in C++. We did this with the help of SFML. We learned to test this service for both local and remote hosts.

Also read: C++ program to find parity of a number efficiently

Leave a Reply