[Bash] How do I work with networking and sockets in Bash?

In Bash, you can work with networking and sockets using the netcat utility (nc command) which is commonly available on most Unix-like systems. Netcat allows you to create TCP or UDP connections, listen for incoming connections, and transfer data over the network. Here are some examples of using netcat for networking in Bash:

  1. To establish a TCP connection with a remote host:
1$ nc <host> <port>

Replace <host> with the hostname or IP address of the remote host and <port> with the port number you want to connect to.

  1. To listen for incoming TCP connections on a specific port:
1$ nc -l <port>

Replace <port> with the port number on which you want to listen for incoming connections.

  1. To send and receive data over a TCP connection:
1$ echo "Hello, Server" | nc <host> <port>

Replace <host> with the hostname or IP address of the remote server and <port> with the port number. The echo command sends the message "Hello, Server" to the remote server.

  1. To create a UDP connection:
1$ echo "Hello, UDP Server" | nc -u -w1 <host> <port>

Replace <host> with the hostname or IP address of the remote server and <port> with the port number. The -u flag specifies UDP mode, and the -w1 flag sets a timeout of 1 second.

These are just a few basic examples of using netcat for networking in Bash. You can explore more options and functionalities by referring to the netcat documentation or by using the -h flag to display the help message.