I’d like to take a program P that reads from stdin & writes to stdout, but connect it to nc or whatever such that it reads from a certain port and outputs to another port.
# The reading is easy, here P reads from port 50505 nc -l 50505 | P
How do I get it to write back to say port 60606?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I you mean that someone may open 2 TCP connections to your machine, one to port 50505 and another to port 60606, send data on the first one intended to be fed to P and expect to read the output of P from the second TCP connection, then that would be:
< /dev/null nc -q -1 -l 50505 | P | nc -l 60606 > /dev/null
Or with socat:
socat -u tcp-listen:50505,reuseaddr - | P | socat -u - tcp-listen:60606,reuseaddr
For P to send its output back to the same connection:
socat tcp-listen:50505,reuseaddr exec:P
Method 2
You don’t need nc in order to work with ports. bash can do that itself:
Bash handles several filenames specially when they are used in redirections, as described in the following table:
/dev/fd/fd
If fd is a valid integer, file descriptor fd is duplicated.
/dev/stdin
File descriptor 0 is duplicated.
/dev/stdout
File descriptor 1 is duplicated.
/dev/stderr
File descriptor 2 is duplicated.
/dev/tcp/host/port
If host is a valid hostname or Internet address, and port is an integer
port number or service name, bash attempts to open a TCP connection to
the corresponding socket.
/dev/udp/host/port
If host is a valid hostname or Internet address, and port is an integer
port number or service name, bash attempts to open a UDP connection to
the corresponding socket.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0