knowledge/technology/applications/cli/network/netcat.md

3.4 KiB
Raw Blame History

obj wiki
application https://en.wikipedia.org/wiki/Netcat

netcat

The nc (or netcat) utility is used for just about anything under the sun involving TCP, UDP, or UNIX-domain sockets. It can open TCP connections, send UDP packets, listen on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6.

Common uses include:

  • simple TCP proxies
  • shell-script based HTTP clients and servers
  • network daemon testing
  • a SOCKS or HTTP ProxyCommand for ssh

Options

Option Description
-4 Use IPv4 addresses only
-6 Use IPv6 addresses only
-b Allow broadcast
-l Listen for an incoming connection rather than initiating a connection to a remote host
-N shutdown the network socket after EOF on the input. Some servers require this to finish their work
-p <source_port> Specify the source port nc should use, subject to privilege restrictions and availability

Examples

Client/Server Model

On one console, start nc listening on a specific port for a connection. For example:

nc -l 1234

nc is now listening on port 1234 for a connection. On a second console (or a second machine), connect to the machine and port being listened on:

nc -N 127.0.0.1 1234

There should now be a connection between the ports. Anything typed at the second console will be concatenated to the first, and vice-versa. After the connection has been set up, nc does not really care which side is being used as a server and which side is being used as a client. The connection may be terminated using an EOF (^D), as the -N flag was given.

Data Transfer

The example in the previous section can be expanded to build a basic data transfer model. Any information input into one end of the connection will be output to the other end, and input and output can be easily captured in order to emulate file transfer.

Start by using nc to listen on a specific port, with output captured into a file:

nc -l 1234 > filename.out

Using a second machine, connect to the listening nc process, feeding it the file which is to be transferred:

nc -N host.example.com 1234 < filename.in

Talking to Servers

It is sometimes useful to talk to servers “by hand” rather than through a user interface. It can aid in troubleshooting, when it might be necessary to verify what data a server is sending in response to commands issued by the client. For example, to retrieve the home page of a web site:

printf "GET / HTTP/1.0\r\n\r\n" | nc host.example.com 80