nc: arbitrary TCP and UDP connections and listens - Linux Manuals (1) (2024)

nc: arbitrary TCP and UDP connections and listens

Command to display nc manual in Linux: $ man 1 nc

NAME

nc - arbitrary TCP and UDP connections and listens

SYNOPSIS

nc[-46bCDdFhklNnrStUuvZz [-I length]][-i interval][-M ttl][-m minttl][-O length][-P proxy_username][-p source_port][-q seconds][-s sourceaddr][-T keyword][-V rtable][-W recvlimit][-w timeout][-X proxy_protocol][-x proxy_address [: port]][destination][port]

DESCRIPTION

Thenc(ornetcat utility is used for just about anything under the sun involving TCP,UDP, orUNIXsockets.It can open TCP connections, send UDP packets, listen on arbitraryTCP and UDP ports, do port scanning, and deal with both IPv4 andIPv6.Unliketelnet(1),ncscripts nicely, and separates error messages onto standard error insteadof sending them to standard output, astelnet(1)does with some.

Common uses include:

  • simple TCP proxies
  • shell-script based HTTP clients and servers
  • network daemon testing
  • a SOCKS or HTTP ProxyCommand forssh(1)
  • and much, much more

The options are as follows:

-4
Use IPv4 addresses only.
-6
Use IPv6 addresses only.
-b
Allow broadcast.
-C
Send CRLF as line-ending. Each line feed (LF) character from the inputdata is translated into CR+LF before being written to the socket. Linefeed characters that are already preceded with a carriage return (CR)are not translated. Received data is not affected.
-D
Enable debugging on the socket.
-d
Do not attempt to read from stdin.
-F
Pass the first connected socket usingsendmsg(2)to stdout and exit.This is useful in conjunction with-Xto havencperform connection setup with a proxy but then leave the rest of theconnection to another program (e.g.ssh(1)using thessh_config5ProxyUseFdpassoption).Cannot be used with-U
-h
Print out thenchelp text and exit.
-I length
Specify the size of the TCP receive buffer.
-i interval
Sleep forintervalseconds between lines of text sent and received.Also causes a delay time between connections to multiple ports.
-k
When a connection is completed, listen for another one.Requires-l When used together with the-uoption, the server socket is not connected and it can receive UDP datagrams frommultiple hosts.
-l
Listen for an incoming connection rather than initiating aconnection to a remote host.Thedestinationandportto listen on can be specified either as non-optional arguments, or withoptions-sand-prespectively.Cannot be used together with-xor-z Additionally, any timeouts specified with the-woption are ignored.
-M ttl
Set the TTL / hop limit of outgoing packets.
-m minttl
Ask the kernel to drop incoming packets whose TTL / hop limit is underminttl
-N
shutdown(2)the network socket after EOF on the input.Some servers require this to finish their work.
-n
Do not perform domain name resolution.If a name cannot be resolved without DNS, an error will be reported.
-O length
Specify the size of the TCP send buffer.
-P proxy_username
Specifies a username to present to a proxy server that requires authentication.If no username is specified then authentication will not be attempted.Proxy authentication is only supported for HTTP CONNECT proxies at present.
-p source_port
Specify the source portncshould use, subject to privilege restrictions and availability.
-q seconds
after EOF on stdin, wait the specified number ofsecondsand then quit. Ifsecondsis negative, wait forever (default). Specifying a non-negativesecondsimplies-N
-r
Choose source and/or destination ports randomlyinstead of sequentially within a range or in the order that the systemassigns them.
-S
Enable the RFC 2385 TCP MD5 signature option.
-s sourceaddr
Set the source address to send packets from,which is useful on machines with multiple interfaces.ForUNIXdatagram sockets, specifies the local temporary socket fileto create and use so that datagrams can be received.Cannot be used together with-x
-T keyword
Change the IPv4 TOS/IPv6 traffic class value.keywordmay be one ofcritical inetcontrol lowcost lowdelay netcontrol throughput reliability or one of the DiffServ Code Points:ef af11 ... af43 cs0 ... cs7 or a number in either hex or decimal.
-t
Send RFC 854 DON'T and WON'T responses to RFC 854 DO and WILL requests.This makes it possible to usencto script telnet sessions.
-U
UseUNIXsockets.Cannot be used together with-For-x
-u
Use UDP instead of TCP.Cannot be used together with-x ForUNIXsockets, use a datagram socket instead of a stream socket.If aUNIXsocket is used, a temporary receiving socket is created in/tmpunless the-sflag is given.
-V rtable
Set the routing table to be used.
-v
Produce more verbose output.
-W recvlimit
Terminate after receivingrecvlimitpackets from the network.
-w timeout
Connections which cannot be established or are idle timeout aftertimeoutseconds.The-wflag has no effect on the-loption, i.e.ncwill listen forever for a connection, with or without the-wflag.The default is no timeout.
-X proxy_protocol
Useproxy_protocolwhen talking to the proxy server.Supported protocols are4(SOCKS v.4),5(SOCKS v.5)andconnect(HTTPS proxy).If the protocol is not specified, SOCKS version 5 is used.
-x proxy_address [: port]
Connect todestinationusing a proxy atproxy_addressandport Ifportis not specified, the well-known port for the proxy protocol is used (1080for SOCKS, 3128 for HTTPS).An IPv6 address can be specified unambiguously by enclosingproxy_addressin square brackets.A proxy cannot be used with any of the options-lsuU
-Z
DCCP mode.
-z
Only scan for listening daemons, without sending any data to them.Cannot be used together with-l

destinationcan be a numerical IP address or a symbolic hostname(unless the-noption is given).In general, a destination must be specified,unless the-loption is given(in which case the local host is used).ForUNIXsockets, a destination is required and is the socket path to connect to(or listen on if the-loption is given).

portcan be specified as a numeric port number or as a service name.Port ranges may be specified as numeric port numbers of the formnn - mm In general,a destination port must be specified,unless the-Uoption is given.

CLIENT/SERVER MODEL

It is quite simple to build a very basic client/server model usingnc.On one console, startnclistening on a specific port for a connection.For example:

$ nc -l 1234

ncis 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,ncdoes 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 anEOF(`^D') as the-Nflag was given.

There is no-cor-eoption in this netcat, but you still can execute a command after connectionbeing established by redirecting file descriptors. Be cautious here becauseopening a port and let anyone connected execute arbitrary command on yoursite is DANGEROUS. If you really need to do this, here is an example:

On`server'side:

$ rm -f /tmp/f; mkfifo /tmp/f
$ cat /tmp/f | /bin/sh -i 2>&1 | nc -l 127.0.0.1 1234 > /tmp/f

On`client'side:

$ nc host.example.com 1234
$ (shell prompt from host.example.com)

By doing this, you create a fifo at /tmp/f and make nc listen at port 1234of address 127.0.0.1 on`server'side, when a`client'establishes a connection successfully to that port, /bin/sh gets executedon`server'side and the shell prompt is given to`client'side.

When connection is terminated,ncquits as well. Use-kif you want it keep listening, but if the command quits this option won'trestart it or keepncrunning. Also don't forget to remove the file descriptor once you don't needit anymore:

$ rm -f /tmp/f

DATA TRANSFER

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

Start by usingncto listen on a specific port, with output captured into a file:

$ nc -l 1234 > filename.out

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

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

After the file has been transferred, the connection will close automatically.

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 sendingin 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

Note that this also displays the headers sent by the web server.They can be filtered, using a tool such assed(1),if necessary.

More complicated examples can be built up when the user knows the formatof requests required by the server.As another example, an email may be submitted to an SMTP server using:

$ nc [-C] localhost 25 << EOFHELO host.example.comMAIL FROM:<user [at] host.example.com>RCPT TO:<user2 [at] host.example.com>DATABody of email..QUITEOF

PORT SCANNING

It may be useful to know which ports are open and running services ona target machine.The-zflag can be used to tellncto report open ports,rather than initiate a connection. Usually it's useful to turn on verboseoutput to stderr by use this option in conjunction with-voption.

For example:

$ nc -zv host.example.com 20-30Connection to host.example.com 22 port [tcp/ssh] succeeded!Connection to host.example.com 25 port [tcp/smtp] succeeded!

The port range was specified to limit the search to ports 20 - 30, and isscanned by increasing order (unless the-rflag is set).

You can also specify a list of ports to scan, for example:

$ nc -zv host.example.com http 20 22-23nc: connect to host.example.com 80 (tcp) failed: Connection refusednc: connect to host.example.com 20 (tcp) failed: Connection refusedConnection to host.example.com port [tcp/ssh] succeeded!nc: connect to host.example.com 23 (tcp) failed: Connection refused

The ports are scanned by the order you given (unless the-rflag is set).

Alternatively, it might be useful to know which server softwareis running, and which versions.This information is often contained within the greeting banners.In order to retrieve these, it is necessary to first make a connection,and then break the connection when the banner has been retrieved.This can be accomplished by specifying a small timeout with the-wflag, or perhaps by issuing aQq Dv QUITcommand to the server:

$ echo "QUIT" | nc host.example.com 20-30SSH-1.99-OpenSSH_3.6.1p2Protocol mismatch.220 host.example.com IMS SMTP Receiver Version 0.84 Ready

EXAMPLES

Open a TCP connection to port 42 of host.example.com, using port 31337 asthe source port, with a timeout of 5 seconds:

$ nc -p 31337 -w 5 host.example.com 42

Open a UDP connection to port 53 of host.example.com:

$ nc -u host.example.com 53

Open a TCP connection to port 42 of host.example.com using 10.1.2.3 as theIP for the local end of the connection:

$ nc -s 10.1.2.3 host.example.com 42

Create and listen on aUNIXstream socket:

$ nc -lU /var/tmp/dsocket

Connect to port 42 of host.example.com via an HTTP proxy at 10.2.3.4,port 8080.This example could also be used byssh(1);see theProxyCommanddirective inssh_config5for more information.

$ nc -x10.2.3.4:8080 -Xconnect host.example.com 42

The same example again, this time enabling proxy authentication with username``ruser''if the proxy requires it:

$ nc -x10.2.3.4:8080 -Xconnect -Pruser host.example.com 42

AUTHORS

Original implementation byAn *Hobbit* Aq Mt hobbit [at] avian.org .
Rewritten with IPv6 support byAn Eric Jackson Aq Mt ericj [at] monkey.org .
Modified for Debian port by Aron XuAq aron [at] debian.org .

CAVEATS

UDP port scans using the-uzcombination of flags will always report success irrespective ofthe target machine's state.However,in conjunction with a traffic sniffer either on the target machineor an intermediary device,the-uzcombination could be useful for communications diagnostics.Note that the amount of UDP traffic generated may be limited eitherdue to hardware resources and/or configuration settings.

SEE ALSO

cat(1),ssh(1)

Pages related to nc

  • nc.openbsd (1) - arbitrary TCP and UDP connections and listens
  • nc2xy (1) - Converting netCDF column file(s) to ASCII xy data
  • nc6 (1) - network swiss army knife
  • nc_openbsd (1) - arbitrary TCP and UDP connections and listens
  • ncal (1) - displays a calendar and the date of Easter
  • ncap (1) - netCDF Arithmetic Processor
  • ncap2 (1) - netCDF Arithmetic Processor, Next Generation
  • ncargcc (1) - Command for compiling C code that uses the NCAR Graphics low-level
  • ncargex (1) - NCAR Graphics Fortran and C Low-Level Utility Examples
  • ncargf77 (1) - Command for compiling Fortran code that uses the NCAR Graphics
  • ncargf90 (1) - Command for compiling Fortran code that uses the NCAR Graphics
  • ncargfile (1) - NCAR Graphics Files
  • Xvnc (1) - the X VNC server

Linux Manuals Copyright Respective Owners. Site Copyright © SysTutorials. All Rights Reserved. Terms and Privacy

nc: arbitrary TCP and UDP connections and listens - Linux Manuals (1) (2024)

References

Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated:

Views: 6219

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.