nagul
nagul

Reputation: 2263

Best way to monitor for a server on a TCP port

I have a remote Music Player Daemon(MPD) server running on a linux machine. I have a client listening to this stream on another linux machine.

When the MPD server is asked to pause or stop the stream, it disconnects all clients connected on the TCP port. Consequently, when the server starts streaming again, the clients have to be manually reconnected.

I want to write a program that will monitor the TCP port for a server accepting connections, and then automatically restart the clients. Can I do better than running connect() and sleep() in a loop? Are there any command-line utilities to do this?

I can run the client on the machine running the MPD server, if it will help. The following will tell me if a process is listening on a local port, but they do not block if a process isn't, so I still need to wrap them in a loop.

$ sudo fuser -n tcp 8000
8000/tcp: 9677

$ sudo netstat -nlp | grep 8000
tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 9677/mpd

I can try any solution that does not involve changing the behaviour of the MPD server.

Upvotes: 1

Views: 3404

Answers (2)

Mark Rushakoff
Mark Rushakoff

Reputation: 258198

Here you go:

echo -n "" | nc -q 0 localhost 8000 && echo "made a connection" || echo "server was down"

echo -n "" puts an EOF immediately on stdin; nc -q 0 returns immediately after seeing that EOF on stdin. nc (netcat) tries to make a connection to localhost on port 8000. If it connects successfully, then it returns a successful error code and we echo "made a connection"; otherwise, if the connection was refused, we echo "server was down".

If you want to test it out, then in another terminal run

nc -lvvp 8000

which will start an instance of netcat listening on port 8000, with verbose output. In your other terminal, run the first command. The first time you run it, it will say made a connection. Then the server/listener will close, so the next time you run it, it will say server was down.

Upvotes: 2

quamrana
quamrana

Reputation: 39354

There is always the possibility of writing a relay server that proxies for MPD.

It sits there listening on a different port for your clients and makes connections to MPD in their stead. When MPD disconnects, the relay just attempts to reconnect every few seconds without disconnecting its clients.

Upvotes: 3

Related Questions