bash-socket

Migrate from https://cmakerhk.wordpress.com/2018/11/05/socket-on-shell/


http://www.tutorialspoint.com/unix_commands/nc.htm
NC: netcat

$nc -l 1234

When you enter http://localhost:1234
you will see

GET / HTTP/1.1
Host: localhost:1234
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

–> How to do a response?

For not a Web client

Server
nc -l 1234 >> Listen TCP on port 1234
nc 127.0.0.1 1234 >> connect to TCP port 1234

then you make a chat room xd

nc -l 1234 > filename.out
nc host.example.com 1234 >>>>>>
echo -n “GET / HTTP/1.0\r\n\r\n” | nc host.example.com 80

-v: display all the information

File Transfer
$ cat happy.txt | ncat -v -l -p 5555
Ncat: Version 5.21 ( http://nmap.org/ncat )
Ncat: Listening on 0.0.0.0:5555
$ ncat localhost 5555 > happy_copy.txt

Port Scanning
TCP
$ nc -v -n -z -w 1 127.0.0.1 8080-8088
nc: connect to 127.0.0.1 port 8080 (tcp) failed: Connection refused
nc: connect to 127.0.0.1 port 8081 (tcp) failed: Connection refused
nc: connect to 127.0.0.1 port 8082 (tcp) failed: Connection refused
Connection to 127.0.0.1 8083 port [tcp/*] succeeded!
nc: connect to 127.0.0.1 port 8084 (tcp) failed: Connection refused
nc: connect to 127.0.0.1 port 8085 (tcp) failed: Connection refused
nc: connect to 127.0.0.1 port 8086 (tcp) failed: Connection refused
nc: connect to 127.0.0.1 port 8087 (tcp) failed: Connection refused
nc: connect to 127.0.0.1 port 8088 (tcp) failed: Connection refused

UDP
$ nc -ul 8083 -v
Listening on [0.0.0.0] (family 0, port 8083)
Connection from localhost 50944 received!
XXXXX
$ nc -u -v -n -z 127.0.0.1 8080-8088
Connection to 127.0.0.1 8083 port [udp/*] succeeded!

“-n” parameter here prevents DNS lookup,
“-z” makes nc not receive any data from the server
“-w 1” makes the connection timeout after 1 second of inactivity