Sergei
Sergei

Reputation: 135

Bridging two ports with netcat/socat

I need to get data from a ModBus device (modbus slave) over TCP but this device has to be exposed as a TCP client (it eats much less from the battery in this case). It means that both machines have to connect to the third one as TCP clients an I have to build a bridge between two ports, something like this

[modbus slave] -> [4444:bridge:5555] <- [modbus master]

I did try it with the netcat on a bridge machine

$ /bin/netcat -lk 5555 | /bin/netcat -lk 4444

It works the half way: I can connect to 4444 with my slave and to 5555 with my master, and traffic flows from master to slave. However, I do not see any traffic in the opposite direction. How do I build a two-way bridge in this case?

Thanks a lot in advance!

Upvotes: 3

Views: 2881

Answers (2)

Katoomba
Katoomba

Reputation: 78

You can have the connections automatically recover after either end disconnects (so that the clients can reconnect immediately). Do this by setting -k flag. Also note, that you probably want to limit the number of connections to 1 on either side using -m parameter. Otherwise, you can bridge thousands of clients together! So putting it all together:

# mkfifo fifo
# nc -lkm1 -p4444 < fifo | nc -lkm1 -p5555 > fifo

Upvotes: 1

some user
some user

Reputation: 1008

You can run 2 netcat instances with a fifo like this:

# mkfifo fifo
# nc -l -p 4444 < fifo | nc -l -p 5555 > fifo

You can also do it using just socat.

# socat TCP4-LISTEN:4444 TCP4-LISTEN:5555

On a side note, I would imagine running a client consumes more power (which needs to keep on connecting) than server (which only waits for incoming connection). Maybe there is some other design consideration that I missed.

Upvotes: 3

Related Questions