Shell – How to create a TCP listener

networkingshelltcp

Introduction: I have created a bash function that is able to check whether a port is available and increments it by 1 if false until a certain maximum port number. E.g., if port 500 is unavailable then the availability of 501 will be checked until 550.

Aim: In order to test this bash function I need to create a range of ports that are in LISTEN state.

Attempts: On Windows it is possible to create a LISTEN port using these PowerShell commands:

PS C:\Users\u> netstat -nat | grep 1234
PS C:\Users\u> $listener = [System.Net.Sockets.TcpListener]1234
PS C:\Users\u> $listener.Start();
PS C:\Users\u> netstat -nat | grep 1234
TCP    0.0.0.0:1234           0.0.0.0:0              LISTENING       InHost
PS C:\Users\u> $listener.Stop();
PS C:\Users\u> netstat -nat | grep 1234
PS C:\Users\u>

Based on this I was trying to think about a command that could do the same on CentOS, but I do not know why and I started to Google without finding a solution that solves this issue.

Expected answer: I will accept and upvote the answer that contains a command that is able to create a LISTEN port and once the command has been run the port should stay in LISTEN state, i.e.:

[user@host ~]$ ss -nat | grep 500
LISTEN     0      128                       *:500                       *:*

Best Answer

You could use nc -l as a method to do what you are looking for. Some implementations of nc have a -L option which allows the connections to persist.

If you only need them for a little while you could open this command in a for loop and have a bunch of ports opened that way.

If you need these opened longer you can use one of the super servers to create a daemon.

Related Question