Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TCP connection, bash only

I found this line in a script. While I globally understand what it does--opening a bidirectional TCP connection--, I need some explanations on the syntax. Here's the line:

exec 5<>"/dev/tcp/${SERVER}/${PORT}" 

And my questions:

  1. < and > are usually used to redirect IOs. What does it mean there? Is it usable in another context? How?
  2. Why does it work, while /dev/tcp doesn't exists?
  3. Why 5? Can it be another number? What are the values allowed?
  4. Why is exec necessary? (given nothing is actually executed)

Thanks.

like image 764
gregseth Avatar asked Oct 14 '11 08:10

gregseth


People also ask

How do I close a TCP connection in Linux?

Use the DRop/-D command to terminate an individual TCP connection when you do not want to terminate the server itself, but want only to drop an individual connection with that server. Use the DROP/-D command to terminate old TCP connections if they prevent a server from being restarted.


1 Answers

< and > are usually used to redirect IOs. What does it mean there? Is it usable in another context? How?

It's the same - input and output is redirected to fd 5.

Why does it work, while /dev/tcp doesn't exists?

It's a special file: 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.

Why 5? Can it be another number? What are the values allowed?

Yes, it can be any value, but you need to ensure you don't use an fd already in use.

Why is exec necessary? (given nothing is actually executed)

exec means the redirection happens in the current shell, not within a subshell.

like image 96
trojanfoe Avatar answered Sep 21 '22 18:09

trojanfoe