1

From what I read (only the very outline, i do not know C Language) a Socket session is established between a server and a client by calling functions for both of them in a certain order.

It starts with the Server:
socket()     #creates communication point
bind()       #gives this communication point an address
listen()     #tells it to be ready for some signal

then the Client:
socket()
connect()    #establishes a line between himself and the listening Server

now both can talk with each other by using read() and write().

Well, this was implemented in the C Programming Language, but could this be done also with the Shell and if so would it make any sense doing it this way?

2

There are several programs for making socket connections from the command line (or via a shell script). The most common is probably netcat, of which there are at least three implementations:

The manual page gives many examples, for example here's how (based on a far more scary example in the man page) you can run bc over a socket:

mkfifo /tmp/f && cat /tmp/f | bc -i 2>&1 | nc -l 127.0.0.1 1234 > /tmp/f

Then you can connect to that network bc using:

nc localhost 1234

Or with socat, it's:

socat EXEC:'bc -i' TCP4-LISTEN:1234,bind=127.0.0.1   # server
socat - TCP4:127.0.0.1:1234                          # client
  • There's also a netcat spin-off called ncat. – Scott Apr 1 '15 at 4:30
  • @Scott indeed. And several more, including an optional bash feature, at least a kernel patch or two, etc. Feel free to edit in any you find important... – derobert Apr 1 '15 at 4:34
  • 1
    The most interesting one I didn't mention is probably socat, I'll add that one in later tonight. – derobert Apr 1 '15 at 4:36
  • ^ yes ^ please do, That's the one I immediately thought of when reading the question. Following the train here, I think socat's command of ptys is particularly relevant to bc. As an aside, a method I generally find convenient when working w/ mkfifo is get an fd on the pipe then deleting the link before going further. Like mkfifo pipe; exec 3<>pipe; rm pipe; <&3 bc | nc >&3 &. It saves the cleanup later and is more secure, I think. – mikeserv Apr 1 '15 at 7:14
  • @mikeserv socat added. I'll note though that your immediate pipe cleanup isn't really any safer—both are only safe if file permissions keep an attacker from opening the pipe or rm'ing it (and replacing with something else, like a symlink) before the intended code opens it – derobert Apr 1 '15 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.