How can I tell if a TCP port is open or not?

45,810

Solution 1

Since you are programming in C I thought of posting a little snippet which shows you if the port is open or not, I have programmed to output a string. You can easily change it to fit your need.

Answer to your second question, like everyone here said, you can pretty much use any port if you are the super user (root) on the system if the port is not used by any other application. If you are not the root then you can open any port above 1024.

#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     = 5454;
    char *hostname = "192.168.56.101";

    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");
        exit(0);
    }

    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,
         server->h_length);

    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");
    }

    close(sockfd);
    return 0;
}

Solution 2

There are several ways, the most common probably being:

# netstat -ltun

You can, of course, grep for other (regular) expression.

If you are using different machines (client and server), you need to check iptables as well.

You can pretty much use any port that's not currently being used for your programs. Check, however, /etc/services for known and reserved ports.

Solution 3

Check the link(http://wi-fizzle.com/article/458) for TCP port is open or not

nc -z <host_or_ip> <port> 1>/dev/null 2>&1; result=$?;

if [ $result -eq 0 ]; then
    echo 'the port is open for tcp connections'
else
    echo 'the port was closed'
fi

Solution 4

The best tool for trying to determine if a process is bound to a TCP port is netstat. You can run it like so to get a list of the name of the process that's bound, if any, as well as any connections to the port, as well as their state.

Example

$ netstat -tapn | head -15
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:49006               0.0.0.0:*                   LISTEN      -                   
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      -                   
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      -                   
tcp        0      0 127.0.0.1:631               0.0.0.0:*                   LISTEN      -                   
tcp        0      0 0.0.0.0:17500               0.0.0.0:*                   LISTEN      3516/dropbox        
tcp        0      0 0.0.0.0:17501               0.0.0.0:*                   LISTEN      3517/dropbox        
tcp        0      0 0.0.0.0:2143                0.0.0.0:*                   LISTEN      4383/ssh            
tcp        0      0 127.0.0.1:1986              0.0.0.0:*                   LISTEN      2757/mono           
tcp        0      0 0.0.0.0:2025                0.0.0.0:*                   LISTEN      4383/ssh            
tcp        0      0 192.168.1.20:58285          198.252.206.25:80           TIME_WAIT   -                   
tcp        0      0 192.168.1.20:58188          198.252.206.25:80           ESTABLISHED 3830/chrome --purge 
tcp        0      0 192.168.1.20:58286          198.252.206.25:80           TIME_WAIT   -                   
tcp        0      0 192.168.1.20:54000          174.37.23.130:6667          ESTABLISHED 2696/pidgin         

The above shows locally opened ports in the 3rd column and remote ports we're willing to accept connections to, such as with these 2 lines:

tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      -                   
tcp        0      0 127.0.0.1:631               0.0.0.0:*                   LISTEN      -                   

These 2 lines show that we're listening on port 22, (sshd) and are willing to accept connections from any interface we have (i.e. any network card, ethernet or wireless). There are currently no connections to this port.

The 2nd line shows that wer're running the CUPS server (for printing) on port 631, and we can only connect to it through the localhost (127.0.0.1) interface.

Further down we have these 2 lines:

tcp        0      0 192.168.1.20:58285          198.252.206.25:80           TIME_WAIT   -                   
tcp        0      0 192.168.1.20:58188          198.252.206.25:80           ESTABLISHED 3830/chrome --purge 

Which show that we're accessing a website at IP address 198.252.206.25. We know it's a website because we're accessing this server through port 80 (HTTP). Also if we look up the IP address we find this:

$ dig -x 198.252.206.25 +short
stackoverflow.com.

Solution 5

Use the command:

nmap 192.168.56.101

It will result the number of ports open on that machine along with name of services

Share:
45,810

Related videos on Youtube

dxr
Author by

dxr

Updated on September 18, 2022

Comments

  • dxr
    dxr over 1 year

    I am trying to implement socket programming in C. When I try to connect from a client to a server (Ubuntu), it shows an error like "connection failed".

    So I think the problem is with the port. I am using the 5454/tcp port for socket programming.

    How can I know if 5454 port is listening or not? If it is not, then which are the ports that I can use for TCP socket programming using C in Ubuntu? Is that the problem with port only or is there anything wrong in my code or any settings is required in LINUX Ubuntu?

    EDIT: Snippet of code:

      int socket_send;
       struct sockaddr_in address;
    printf("\n Initialization Socket....");
    
    socket_send = socket(AF_INET,SOCK_STREAM,0);
    if(socket_send == -1)
    {
        perror("\n Socket not created.Error:");
        return 1;
    }
    printf("\n Socket created");
    
    address.sin_family=AF_INET;
    address.sin_addr.s_addr=inet_addr(ip);
    address.sin_port=htons(5454);
    
    if(connect(socket_send,(struct sockaddr*)&address,sizeof(struct sockaddr))<0)
    {
        perror("\nConnetion failed.Error:");
        return 1;
    }
    printf("\n Connected");
    
    if(send(socket_send,(char*)buffer,size,flag)<0)
    {
        perror("\nSending failed.Error:");
        return 1;
    }
    printf("\n Data successfully sent");
     close(socket_send);
    

    EDIT: Problem is in port, so I just re installed Ubuntu, and it's working. Thank you all of you.

    • Admin
      Admin over 10 years
      at first, port 5454 should listen state, Then you connect.second check your firewall.
    • Admin
      Admin over 10 years
      I always try lsof -i:5454 (you may need to execute it as the same user that the program opening the port does, or as root).
    • Admin
      Admin over 10 years
      where's the server code (or is the server an existing program) Note that if you want to run a dummy server, nc (netcat) is your friend.
  • dsmsk80
    dsmsk80 over 10 years
    You can directly list tcp/udp ports in listen state with "netstat -ltun"
  • dawud
    dawud over 10 years
    @dsmsk80 ah, indeed, I guess bad habits die hard. Corrected.
  • Marek Zakrzewski
    Marek Zakrzewski over 10 years
    Excellent! way to check a ports' status using C.
  • Olivier Dulac
    Olivier Dulac over 10 years
    I love the mention "a little snippet" ^^. But +1 for a very informative snippet.
  • jwg
    jwg over 10 years
    Using anything but nmap for this is beating around the bush IMHO. To check a single port you should use nmap -p5454 192.168.56.101.
  • JZeolla
    JZeolla over 10 years
    This only answers the title but doesn't answer the actual question.
  • SHW
    SHW over 10 years
    Yes. I was just showing the direction. He has to walk to get desired answer. :)
  • Ton van den Heuvel
    Ton van den Heuvel over 6 years
    Note, in case this code runs concurrently with other threads that possible fork() new processes, it is required to ensure that the socket file descriptor is closed properly by specifying SOCK_CLOEXEC for the socket() call.