Check if Port is Open on Linux using C++

Check if Port is Open on Linux using C++

Networking applications often require checking whether a specific port on a remote server is open or closed. This information is crucial for establishing connections and ensuring seamless communication between different devices. This tutorial demonstrates how to check if a port is open on Linux using C++.

The code establishes a connection to a specified hostname and port using sockets. It first creates a socket, checks for errors, and retrieves the host's IP address using the hostname. Then, it sets up a sockaddr_in structure with the host's IP address and port number. After that, it attempts to connect to the specified address. The code determines whether the connection was successful or not and prints the corresponding message accordingly. Finally, it closes the socket and exits.

#include <iostream>
#include <unistd.h>
#include <cstring>
#include <netdb.h>

int main()
{
    const char *hostname = "localhost";
    const int port = 80;

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        std::cerr << "Failed to create socket" << std::endl;
        exit(1);
    }

    struct hostent *server = gethostbyname(hostname);
    if (server == nullptr) {
        std::cerr << "Failed to get host by name" << std::endl;
        exit(1);
    }

    struct sockaddr_in addr{};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    bcopy((char *) server->h_addr, (char *) &addr.sin_addr.s_addr, server->h_length);

    if (connect(sockfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
        std::cout << "Port is closed" << std::endl;
    } else {
        std::cout << "Port is open" << std::endl;
    }
    close(sockfd);

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.