Perl-NW-Oneliner Listening on TCP port

Preface

Sometime it’s needed to run TCP port test, to destination server where we don’t have any application that is able to listen on the particular TCP port.

This document will present simply Perl one-liner solution that will listen on particular TCP port.

Listen on TCP port

At end of this command it’s needed to replace “<TCP_PORT>” with the port number where the script need to listen.

# tcpport=<TCP_PORT> ;

# perl -MIO::Socket -e '$srv=IO::Socket::INET->new(LocalPort=>$ARGV[0],Type=>SOCK_STREAM,Reuse=>1,Listen=>5) or die "Failed to listen on $ARGV[0]\n";while($cl=$srv->accept())  { while(<$cl>) { print } } close($socket);' $tcpport ;

Example

Check TCP port if its free

# netstat -na | grep 2222                                       # Check if on port "2222" is somethin listening
#                                                               # it's free

Start Listening

# tcpport="2222" ;                                              # TCP port to listen

# perl -MIO::Socket -e '$srv=IO::Socket::INET->new(LocalPort=>$ARGV[0],Type=>SOCK_STREAM,Reuse=>1,Listen=>5) or die "Failed to listen on $ARGV[0]\n";while($cl=$srv->accept())  { while(<$cl>) { print } } close($socket);' $tcpport ;

Check TCP port if its listening

# netstat -nap | grep 2222                                       # Check if there is process listening on our TCP port
tcp        0      0 0.0.0.0:2222            0.0.0.0:*               LISTEN      11104/perl

Connect to Destination IP and TCP port

We'll just connect to destination server on the port and send there a message text:

# telnet 127.0.0.1 2222                                          # Connect to the Destination IP on the TCP port
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Hallo, this is a test message                                    # Message that was sent to the Destination IP on TCP port
^]q                                                              # End Telnet session ( "CTRL+]" -> "q" -> "Enter" )

telnet> q
Connection closed.

Check Connection on Destination

At the destination server we'll see the message taht was to the process listening on the TCP port:

# perl -MIO::Socket -e '$srv=IO::Socket::INET->new(LocalPort=>$ARGV[0],Type=>SOCK_STREAM,Reuse=>1,Listen=>5) or die "Failed to listen on $ARGV[0]\n";while($cl=$srv->accept())  { while(<$cl>) { print } } close($socket);' $tcpport ;
Hallo, this is a test message                                      # Message at sent to Destination IP on TCP port
Navigation
Print/export
QR Code
QR Code wiki:programming_languages:perl:perl-nw-oneliner_listening_on_tcp_port (generated for current page)