How to check if a Port is open or not in C (Unix/Linux)

Thought of posting this script as I found this useful to embed in any socket based programs to figure out if a port is open or not in a certain host.
Tested on a Linux box and appears to be working fine.

Localhost and port 22 is hard coded into the snippet.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

int main(int argc, char *argv[])
    int portno     = 22;
    char *hostname = "localhost;

    int sockfd;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        error("ERROR opening socket");

    server = gethostbyname(hostname);

    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");

    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
         (char *)&serv_addr.sin_addr.s_addr,

    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
        printf("Port is closed");
    } else {
        printf("Port is active");

    return 0;

One thought on “How to check if a Port is open or not in C (Unix/Linux)

  1. Mac looses everytime. Been using Mac for over 15 years and dumped it for LinuxMint 17.3 Mate. I’m a real Newbie to Linux but it wins hands down. It feels like Mac used to, solid. Mac 10.11.1 is very buggy and insecure, apple has turned it into a recording/reporting machine. I’m running a late 2014 Mac Mini and with Linux my machine runs smoother and quieter, if that can be? but it does, honest. I’ll figure out how to use Linux in due time, I love to tweak things like the way mac used to be. Thanks for your site. Lots of clues here on what to do. BTW, I like Rabbits too. You may want to visit my site to see what mac really does.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s