w1100n
w1100n

Reputation: 1668

How to test a remote port is reachable with socat

How to test a remote port is reachable with socat?

with netcat we can

nc -zv 192.168.1.15 22

How to do that with socat?

Upvotes: 18

Views: 15533

Answers (3)

Seamus
Seamus

Reputation: 223

Here's a brief test I use in my bash scripts (probably works in zsh also):

while :
do
    socat /dev/null TCP4:google.com:443 && break
    sleep 60
done

socat is placed inside an infinite loop (while :); when it succeeds (i.e. the Internet is connected to my LAN) the break is executed which exits the loop. If it fails, it sleeps for 1 minute (sleep 60), and socat tests the connection again. I've found this effective in avoiding script failures due to short-term Internet outages.

Upvotes: 1

Archimedes Trajano
Archimedes Trajano

Reputation: 41290

As the OP requested the equivalent of -z the following socat command will ensure that it does not wait for input and just checks if the port is listening or not.

socat /dev/null TCP:remote:port

This can be used in a Docker context especially on health checks for the alpine/socat image. Here is an example that sets up a forwarder for the smtp service to a mailhog service and checks if the connection is up

services:
  smtp:
    image: alpine/socat
    command: tcp-listen:25,fork TCP:mailhog:1025
    healthcheck: socat /dev/null TCP:mailhog:1025

Upvotes: 18

Lars Nordin
Lars Nordin

Reputation: 2828

I would imagine that the first example in the man page would work

socat - TCP4:www.domain.org:80

For your example, this would be (and adding 2 second connect timeout):

socat - TCP4:192.168.1.15:22,connect-timeout=2

and the response would be the sshd connect banner (if that is what is listening)

SSH-2.0-OpenSSH_5.3

or

socat[12650] E connecting to AF=2 192.168.189.6:23: Connection timed out

Upvotes: 4

Related Questions