Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Socat -- reading from and writing to network connections on either TCP or UDP

News See Also Recommended Links cat command Pipes Sockets Nmap
dd and netcat pv ntop nettee ngrep Humor Etc

The socat is a version of netcat and can be used as a relay for bidirectional data transfers between two independent data channels.

There are several channels socat can connect, including:

This tool is regarded as the advanced version of netcat. They do similar things, but socat has more additional functionality, such as permitting multiple clients to listen on a port, or reusing connections.

Why do we need socat?

Here are a few examples:

How do we use socat?

The syntax for socat is fairly simple:

socat [options] <address> <address>

You must provide the source and destination addresses for it to work. The syntax for these addresses is:

protocol:ip:port

Examples of using socat

Let's get started with some basic examples of using socat for various connections.

1. Connect to TCP port 80 on the local or remote system:

# socat - TCP4:www.example.com:80

In this case, socat transfers data between STDIO (-) and a TCP4 connection to port 80 on a host named www.example.com.

2. Use socat as a TCP port forwarder:

For a single connection, enter:

# socat TCP4-LISTEN:81 TCP4:192.168.1.10:80

For multiple connections, use the fork option as used in the examples below:

# socat TCP4-LISTEN:81,fork,reuseaddr TCP4:TCP4:192.168.1.10:80

This example listens on port 81, accepts connections, and forwards the connections to port 80 on the remote host.

# socat TCP-LISTEN:3307,reuseaddr,fork UNIX-CONNECT:/var/lib/mysql/mysql.sock 

The above example listens on port 3307, accepts connections, and forwards the connections to a Unix socket on the remote host.

3. Implement a simple network-based message collector:

# socat -u TCP4-LISTEN:3334,reuseaddr,fork OPEN:/tmp/test.log,creat,append

In this example, when a client connects to port 3334, a new child process is generated. All data sent by the clients is appended to the file /tmp/test.log. If the file does not exist, socat creates it. The option reuseaddr allows an immediate restart of the server process.

4. Send a broadcast to the local network:

# socat - UDP4-DATAGRAM:224.255.0.1:6666,bind=:6666,ip-add-membership=224.255.0.1:eth0

In this case, socat transfers data from stdin to the specified multicast address using UDP over port 6666 for both the local and remote connections. The command also tells the interface eth0 to accept multicast packets for the given group.

Practical uses for socat

Socat can be used for troubleshooting of TCP/IP connections. It is also handy for easily making remote connections. P

I use socat to connect my web application to a remote MySQL server by connecting over the local socket.

1. On my remote MySQL server, I enter:

# socat TCP-LISTEN:3307,reuseaddr,fork UNIX-CONNECT:/var/lib/mysql/mysql.sock &

This command starts socat and configures it to listen by using port 3307.

2. On my webserver, I enter:

# socat UNIX-LISTEN:/var/lib/mysql/mysql.sock,fork,reuseaddr,unlink-early,user=mysql,group=mysql,mode=777 TCP:192.168.100.5:3307 &

The above command connects to the remote server 192.168.100.5 by using port 3307.

However, all communication will be done on the Unix socket /var/lib/mysql/mysql.sock, and this makes it appear to be a local server.

Wrap up

Follow this link to read more examples of using socat.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Jun 28, 2020] Getting started with socat, a multipurpose relay tool for Linux - Enable Sysadmin

Jun 28, 2020 | www.redhat.com

The socat utility is a relay for bidirectional data transfers between two independent data channels.

There are many different types of channels socat can connect, including:

This tool is regarded as the advanced version of netcat . They do similar things, but socat has more additional functionality, such as permitting multiple clients to listen on a port, or reusing connections.

Why do we need socat?

There are many ways to use socate effectively. Here are a few examples:

How do we use socat?

The syntax for socat is fairly simple:

socat [options] <address> <address>

You must provide the source and destination addresses for it to work. The syntax for these addresses is:

protocol:ip:port
Examples of using socat

Let's get started with some basic examples of using socat for various connections.

1. Connect to TCP port 80 on the local or remote system:

# socat - TCP4:www.example.com:80

In this case, socat transfers data between STDIO (-) and a TCP4 connection to port 80 on a host named www.example.com.

2. Use socat as a TCP port forwarder:

For a single connection, enter:

# socat TCP4-LISTEN:81 TCP4:192.168.1.10:80

For multiple connections, use the fork option as used in the examples below:

# socat TCP4-LISTEN:81,fork,reuseaddr TCP4:TCP4:192.168.1.10:80

This example listens on port 81, accepts connections, and forwards the connections to port 80 on the remote host.

# socat TCP-LISTEN:3307,reuseaddr,fork UNIX-CONNECT:/var/lib/mysql/mysql.sock

The above example listens on port 3307, accepts connections, and forwards the connections to a Unix socket on the remote host.

3. Implement a simple network-based message collector:

# socat -u TCP4-LISTEN:3334,reuseaddr,fork OPEN:/tmp/test.log,creat,append

In this example, when a client connects to port 3334, a new child process is generated. All data sent by the clients is appended to the file /tmp/test.log . If the file does not exist, socat creates it. The option reuseaddr allows an immediate restart of the server process.

4. Send a broadcast to the local network:

# socat - UDP4-DATAGRAM:224.255.0.1:6666,bind=:6666,ip-add-membership=224.255.0.1:eth0

In this case, socat transfers data from stdin to the specified multicast address using UDP over port 6666 for both the local and remote connections. The command also tells the interface eth0 to accept multicast packets for the given group.

Practical uses for socat

Socat is a great tool for troubleshooting. It is also handy for easily making remote connections. Practically, I have used socat for remote MySQL connections. In the example below, I demonstrate how I use socat to connect my web application to a remote MySQL server by connecting over the local socket.

1. On my remote MySQL server, I enter:

# socat TCP-LISTEN:3307,reuseaddr,fork UNIX-CONNECT:/var/lib/mysql/mysql.sock &

This command starts socat and configures it to listen by using port 3307.

2. On my webserver, I enter:

# socat UNIX-LISTEN:/var/lib/mysql/mysql.sock,fork,reuseaddr,unlink-early,user=mysql,group=mysql,mode=777 TCP:192.168.100.5:3307 &

The above command connects to the remote server 192.168.100.5 by using port 3307.

However, all communication will be done on the Unix socket /var/lib/mysql/mysql.sock , and this makes it appear to be a local server.

Wrap up

socat is a sophisticated utility and indeed an excellent tool for every sysadmin to get things done and for troubleshooting. Follow this link to read more examples of using socat .

[Jan 19, 2019] NC command (NCAT) for beginners by Shusain

LinuxTechLab

NC command (NCAT) for beginners

NC command is for performing maintenance/diagnosis tasks related to network . It can perform operations like read,write or data redirections over the network, similar to how you can use cat command to manipulate files on Linux system. Nc command can be used as a utility to scan ports, monitoring or can also act as a basic TCP proxy.

Organizations can utilize it to review their network security, web servers, telnet servers, mail servers and so on, by checking the ports that are opened and then secure them. NC command can also be used to capture information being sent by system.

Recommended Read : Top 7 commands for Linux Network Traffic Monitoring

Also Read : Important PostgreSQL commands you should know

Now let's discuss how we can use NC command with some examples,

Examples for NC command

Connect to a remote server

Following example shows how we can connect to remote server with nc command,

$ nc 10.10.10.100 80

here, 10.10.10.100 is IP of the server we want to connect to & 80 is the port number for the remote server. Once connected we can perform some other functions like we can get the total page content with

GET/HTTP/1.1

or fetch page name,

GET/HTTP/1.1

or we can get banner for OS fingerprinting with the following,

HEAD/HTTP/1.1

This will let us know what software & version is being utilised to run the webserver.


Listen to inbound connection requests

To check a server for incoming connection request on a port number, use following example

$ nc -l 8080

Now NC is in listening mode to check port 8080 for incoming connection requests. Now listening mode will keep on running, until terminated manually. But we can address this option 'w' for NC,

$ nc -w 10 8080

here, 10 means NC will listen for connections for 10 seconds only.


Connecting to UDP ports

By default, we can connect to TCP ports with NC but to listen to incoming request made to UDP ports we have to use option 'u' ,

$ nc -l -u 55


Using NC for Port forwarding

With option 'c' of NC, we can redirect a port to another. Complete example is,

$ nc -u -l 8080 -c ' nc -u -l 8090'

here, we have forwarded all incoming requests from port 8080 to port 8090.


Using NC as Proxy server

To use NC command as a proxy, use

$ nc – l 8080 | nc 10.10.10.200 80

here, all incoming connections to port 8080 will be diverted to 10.10.10.200 server on port 80.

Now with the above command, we only created a one way passage. To create a return passage or 2 way communication channel, use the following commands,

$ mkfifo 2way

$ nc – l 8080 0<2way | nc 10.10.10.200 80 1>2way

Now you will have the capacity to send and get information over nc proxy.


Using NC as chat tool

Another utility that NC command can serve is as a chat tool. Yes we can also use it as a chat. To create it, first run the following command on one server,

$ nc – l 8080

Than to connect on remote machine, run

$ nc 10.10.10.100 8080

Now we can start conversation using the terminal/CLI.


Using NC to create a system backdoor

Now this one is the most common application of NC & is mostly used by hackers a lot. Basically this creates a backdoor to system which can be exploited by hackers (you should not be doing it, its wrong). One must be aware of this as to safeguard against this kind of exploits.

Following command can be used to create a backdoor,

$ nc -l 5500 -e /bin/bash

here, we have attached port 5500 to /bin/bash, which can now be connected from a remote machine to execute the commands,

$ nc 10.10.10.100 5500


Force server to remain up

Server will stop listening for connection once a client connection has been terminated. But with option 'k', we can force a server to remain running, even when no client is connected.

$ nc -l -k 8080


We now end this tutorial on how to use NC command, please feel free to send in any questions or queries you have regarding this article.

[Dec 01, 2015] Linux and Unix Port Scanning With netcat [nc] Command

If nmap is not installed try nc / netcat command as follow. The -z flag can be used to tell nc to report open ports, rather than initiate a connection. Run nc command with -z flag. You need to specify host name / ip along with the port range to limit and speedup operation:
## syntax ##
nc -z -v {host-name-here} {port-range-here}
nc -z -v host-name-here ssh
nc -z -v host-name-here 22
nc -w 1 -z -v server-name-here port-Number-her
 
## scan 1 to 1023 ports ##
nc -zv vip-1.vsnl.nixcraft.in 1-1023

Sample outputs:

Connection to localhost 25 port [tcp/smtp] succeeded!
Connection to vip-1.vsnl.nixcraft.in 25 port [tcp/smtp] succeeded!
Connection to vip-1.vsnl.nixcraft.in 80 port [tcp/http] succeeded!
Connection to vip-1.vsnl.nixcraft.in 143 port [tcp/imap] succeeded!
Connection to vip-1.vsnl.nixcraft.in 199 port [tcp/smux] succeeded!
Connection to vip-1.vsnl.nixcraft.in 783 port [tcp/*] succeeded!
Connection to vip-1.vsnl.nixcraft.in 904 port [tcp/vmware-authd] succeeded!
Connection to vip-1.vsnl.nixcraft.in 993 port [tcp/imaps] succeeded!

You can scan individual port too:

nc -zv v.txvip1 443
nc -zv v.txvip1 80
nc -zv v.txvip1 22
nc -zv v.txvip1 21
nc -zv v.txvip1 smtp
nc -zvn v.txvip1 ftp
 
## really fast scanner with 1 timeout value ##
netcat -v -z -n -w 1 v.txvip1 1-1023

[Jan 12, 2014] Netcat – a couple of useful examples by George Notaras

November 6, 2006 | G-Loaded Journal

One of the Linux command line tools I had initially under-estimated is netcat or just nc. By default, netcat creates a TCP socket either in listening mode (server socket) or a socket that is used in order to connect to a server (client mode). Actually, netcat does not care whether the socket is meant to be a server or a client. All it does is to take the data from stdin and transfer it to the other end across the network.

The simplest example of its usage is to create a server-client chat system. Although this is a very primitive way to chat, it shows how netcat works. In the following examples it is assumed that the machine that creates the listening socket (server) has the 192.168.0.1 IP address. So, create the chat server on this machine and set it to listen to 3333 TCP port:

$ nc -l 3333

On the other end, connect to the server with the following:

$ nc 192.168.0.1 3333

In this case, the keyboard acts as the stdin. Anything you type in the server machine's terminal is transfered to the client machine and vice-versa.

Transfering Files

In the very same way it can be used to transfer files between two computers. You can create a server that serves the file with the following:

$ cat backup.iso | nc -l 3333

Receive backup.iso on the client machine with the following:

$ nc 192.168.0.1 3333 > backup.iso

As you may have noticed, netcat does not show any info about the progress of the data transfer. This is inconvenient when dealing with large files. In such cases, a pipe-monitoring utility like pv can be used to show a progress indicator. For example, the following shows the total amount of data that has been transfered in real-time on the server side:

$ cat backup.iso | pv -b | nc -l 3333

Of course, the same can be implemented on the client side by piping netcat's output through pv:

$ nc 192.168.0.1 3333 | pv -b > backup.iso

Other Examples

Netcat is extremely useful for creating a partition image and sending it to a remote machine on-the-fly:

$ dd if=/dev/hdb5 | gzip -9 | nc -l 3333

On the remote machine, connect to the server and receive the partition image with the following command:

$ nc 192.168.0.1 3333 | pv -b > myhdb5partition.img.gz

This might not be as classy as the partition backups using partimage, but it is efficient.

Another useful thing is to compress the critical files on the server machine with tar and have them pulled by a remote machine:

$ tar -czf - /etc/ | nc -l 3333

As you can see, there is a dash in the tar options instead of a filename. This is because tar's output needs to be passed to netcat.

On the remote machine, the backup is pulled in the same way as before:

$ nc 192.168.0.1 3333 | pv -b > mybackup.tar.gz
Security

It is obvious that using netcat in the way described above, the data travels in the clear across the network. This is acceptable in case of a local network, but, in case of transfers across the internet, then it would be a wise choice to do it through an SSH tunnel.

Using an SSH tunnel has two advantages:

  1. The data is transfered inside an encrypted tunnel, so it is well-protected.
  2. You do not need to keep any open ports in the firewall configuration of the machine that will act as the server, as the connections will take place through SSH.

You pipe the file to a listening socket on the server machine in the same way as before. It is assumed that an SSH server runs on this machine too.

$ cat backup.iso | nc -l 3333

On the client machine connect to the listening socket through an SSH tunnel:

$ ssh -f -L 23333:127.0.0.1:3333 [email protected] sleep 10; \
        nc 127.0.0.1 23333 | pv -b > backup.iso

This way of creating and using the SSH tunnel has the advantage that the tunnel is automagically closed after file transfer finishes. For more information and explanation about it please read my article about auto-closing SSH tunnels.

Telnet-like Usage

Netcat can be used in order to talk to servers like telnet does. For example, in order to get the definition of the word "server" from the "WordNet" database at the dict.org dictionary server, I'd do:

$ nc dict.org 2628
220 ..............some WELCOME.....
DEFINE wn server
150 1 definitions retrieved
151 "server" wn "WordNet (r) 2.0"
server
     n 1: a person whose occupation is to serve at table (as in a
          restaurant) [syn: {waiter}]
     2: (court games) the player who serves to start a point
     3: (computer science) a computer that provides client stations
        with access to files and printers as shared resources to a
        computer network [syn: {host}]
     4: utensil used in serving food or drink
.
250 ok [d/m/c = 1/0/18; 0.000r 0.000u 0.000s]
QUIT
221 bye [d/m/c = 0/0/0; 16.000r 0.000u 0.000s]
Works as a Port Scanner too

A useful command line flag is -z. When it is used, netcat does not initiate a connection to the server, but just informs about the open port it has found. Also, instead of a single port, it can accept a port-range to scan. For example:

$ nc -z 192.168.0.1 80-90
Connection to 192.168.0.1 80 port [tcp/http] succeeded!

In this example, netcat scanned the 80-90 range of ports and reported that port 80 is open on the remote machine.

The man page contains some more interesting examples, so take the time to read it.

... ... ...

[Jan 12, 2014] Linux Netcat command - The swiss army knife of networking

MyLinuxBook

Port scanning is done by system admin and hackers to find the open ports at some machine. It helps them to identify the venerability in the system.

$nc -z -v -n 172.31.100.7 21-25

It can work in both TCP and UDP mode, default is TCP mode, to change to udp use -u option

z option tell netcat to use zero IO .i.e the connection is closed as soon as it opens and no actual data exchange take place.
v option is used for verbose option.
n option tell netcat not to use the DNS lookup for the address.

This command will print all the open ports between 21 to 25.

Banner is a text that services sends when you connects to them. Banner are very usefull when you are trying to velberability in the system as it identify the type and version of the services. NOTE not all services may send banner.
Once You have found the open ports you can easily grab the service banner by connecting to them using netcat.

$ nc -v 172.31.100.7 21

The Linux netcat command will connect to open port 21 and will print the banner of the service running at that port.

[Jan 19, 2011] Image software LinkedIn

Leon Waldman

I always bet on dd + netcat to do imaging over network.

On the system where you will store the image (192.168.0.10):
netcat –l –p 7000 > file.iso


On the system to be cloned:
dd if=/dev/sda | netcat 192.168.0.10 7000 -q
where: dd if=volume_to_be_cloned| netcat ip_of_destination_ip port -q

You can even do it to full clone the system instead store it.

Give a look here:
http://digiassn.blogspot.com/2006/01/dd-over-netcat-for-cheap-ghost.html

Ncat - Netcat for the 21st Century

Ncat is a feature-packed networking utility which will read and write data across a network from the command line. Ncat was written for the Nmap Project as a much-improved reimplementation of the venerable Netcat. It uses both TCP and UDP for communication and is designed to be a reliable back-end tool to instantly provide network connectivity to other applications and users. Ncat will not only work with IPv4 and IPv6 but provides the user with a virtually limitless number of potential uses.

Among Ncat's vast number of features there is the ability to chain Ncats together, redirect both TCP and UDP ports to other sites, SSL support, and proxy connections via SOCKS4 or HTTP (CONNECT method) proxies (with optional proxy authentication as well). Some general principles apply to most applications and thus give you the capability of instantly adding networking support to software that would normally never support it.

Ncat is integrated with Nmap in the latest SVN revision and is also available in Nmap version 4.85BETA1 and later (see the Nmap download page).

The Ncat Users' Guide contains full documentation including many tips, tricks, and practical real-life examples! There is also an Ncat man page for a quick usage summary.

AIX 5L Open Source Packages Main - netcat

Netcat is a simple Unix utility that reads and writes data across network connections, using TCP or UDP protocols. It is designed to be a reliable "back-end" tool that can be used directly or easily driven by other programs and scripts. At the same time, it is a feature-rich network debugging and exploration tool, since it can create almost any kind of connection you may need and has several interesting built-in capabilities.

You can find the documentation in /opt/freeware/share/doc/packages/netcat/README.

Homepage: http://www.vulnwatch.org/netcat/

Current version: v1.10

RPMs:

Source RPM:

[May 12, 2010] Netcat – a couple of useful examples

The simplest example of its usage is to create a server-client chat system. Although this is a very primitive way to chat, it shows how netcat works. In the following examples it is assumed that the machine that creates the listening socket (server) has the 192.168.0.1 IP address. So, create the chat server on this machine and set it to listen to 3333 TCP port:

$ nc -l 3333

On the other end, connect to the server with the following:

$ nc 192.168.0.1 3333

In this case, the keyboard acts as the stdin. Anything you type in the server machine's terminal is transfered to the client machine and vice-versa.

Transfering Files

In the very same way it can be used to transfer files between two computers. You can create a server that serves the file with the following:

$ cat backup.iso | nc -l 3333

Receive backup.iso on the client machine with the following:

$ nc 192.168.0.1 3333 > backup.iso

As you may have noticed, netcat does not show any info about the progress of the data transfer. This is inconvenient when dealing with large files. In such cases, a pipe-monitoring utility like pv can be used to show a progress indicator. For example, the following shows the total amount of data that has been transfered in real-time on the server side:

$ cat backup.iso | pv -b | nc -l 3333

Of course, the same can be implemented on the client side by piping netcat's output through pv:

$ nc 192.168.0.1 3333 | pv -b > backup.iso
Other Examples

Netcat is extremely useful for creating a partition image and sending it to a remote machine on-the-fly:

$ dd if=/dev/hdb5 | gzip -9 | nc -l 3333

On the remote machine, connect to the server and receive the partition image with the following command:

$ nc 192.168.0.1 3333 | pv -b > myhdb5partition.img.gz

This might not be as classy as the partition backups using partimage, but it is efficient.

Another useful thing is to compress the critical files on the server machine with tar and have them pulled by a remote machine:

$ tar -czf - /etc/ | nc -l 3333

As you can see, there is a dash in the tar options instead of a filename. This is because tar's output needs to be passed to netcat.

On the remote machine, the backup is pulled in the same way as before:

$ nc 192.168.0.1 3333 | pv -b > mybackup.tar.gz

Security

It is obvious that using netcat in the way described above, the data travels in the clear across the network. This is acceptable in case of a local network, but, in case of transfers across the internet, then it would be a wise choice to do it through an SSH tunnel.

Using an SSH tunnel has two advantages:

  1. The data is transfered inside an encrypted tunnel, so it is well-protected.
  2. You do not need to keep any open ports in the firewall configuration of the machine that will act as the server, as the connections will take place through SSH.

You pipe the file to a listening socket on the server machine in the same way as before. It is assumed that an SSH server runs on this machine too.

$ cat backup.iso | nc -l 3333

On the client machine connect to the listening socket through an SSH tunnel:

$ ssh -f -L 23333:127.0.0.1:3333 [email protected] sleep 10; \
        nc 127.0.0.1 23333 | pv -b > backup.iso

This way of creating and using the SSH tunnel has the advantage that the tunnel is automagically closed after file transfer finishes. For more information and explanation about it please read my article about auto-closing SSH tunnels.

Telnet-like Usage

Netcat can be used in order to talk to servers like telnet does. For example, in order to get the definition of the word "server" from the "WordNet" database at the dict.org dictionary server, I'd do:

$ nc dict.org 2628
220 ..............some WELCOME.....
DEFINE wn server
150 1 definitions retrieved
151 "server" wn "WordNet (r) 2.0"
server
     n 1: a person whose occupation is to serve at table (as in a
          restaurant) [syn: {waiter}]
     2: (court games) the player who serves to start a point
     3: (computer science) a computer that provides client stations
        with access to files and printers as shared resources to a
        computer network [syn: {host}]
     4: utensil used in serving food or drink
.
250 ok [d/m/c = 1/0/18; 0.000r 0.000u 0.000s]
QUIT
221 bye [d/m/c = 0/0/0; 16.000r 0.000u 0.000s]

Works as a Port Scanner too

A useful command line flag is -z. When it is used, netcat does not initiate a connection to the server, but just informs about the open port it has found. Also, instead of a single port, it can accept a port-range to scan. For example:

$ nc -z 192.168.0.1 80-90
Connection to 192.168.0.1 80 port [tcp/http] succeeded!

In this example, netcat scanned the 80-90 range of ports and reported that port 80 is open on the remote machine.

The man page contains some more interesting examples, so take the time to read it.

socat

2009/05/09: on RedHat based systems CFLAGS may have -Wall predefined which breaks socat's build process with something like #error HAVE_BASIC_OFF_T is out of range: HAVE_BASIC_OFF_T..., please report this as bug. In this case replace the configure file with this version (resp. configure.gz or configure.in) and restart the build process:
make distclean; ./configure; make.

2009/05/07: socat version 1.7.1.1 fixes a couple of bugs, some of which could crash socat under some circumstances (CHANGES).

2009/04/13: Gentil Kiwi updated his Cygwin based binary socat packages at http://www.gentilkiwi.com/telechargements-s43-t-socat.htm#englishversion.

2009/04/04: the third beta version (2.0.0-b3) of socat version 2 is ready for download. It contains all new bug fixes and features of 1.7.1.0 (plus fix:setenv, see below) and introduces the possibility to integrate external programs in address chains (see doc/socat-addresschain.html and doc/socat-exec.html).

2009/04/03: Todd Stansell reported a bug that crashed socat versions 1.7.0.0 to 1.7.1.0 (and all earlier versions with option su) on systems without a native setenv() function, especially Solaris up to version 9. Here is the patch.

2009/04/02: socat version 1.7.1.0 provides a few new address options to better control its closing behaviour - see CHANGES.

2009/04/01: socat version 1.7.0.1 fixes some bugs (connect-timeout, SIGSEGV on listen, end-close).

2008/11/01: a public git repository containing socat 1.6.0.0 and all later releases is available.

2008/10/15: socat version 1.7.0.0 brings support for SCTP stream, raw interface, and generic sockets. New option escape allows to interrupt raw terminal connections. Listening and receiving sockets can set a couple of environment variables. Added base control of System V STREAMS. Lots of corrections were performed. socat compiles on Mac OS X again.

Useful Uses Of netcat HowtoForge - Linux Howtos and Tutorials

1 Preliminary Note

I'm using two systems in this article:

netcat should already be installed on your system - you can check with

which nc

To learn more about netcat, take a look at its man page:

man nc

2 Copying A File From One System To The Other

Let's say we want to copy the file ISPConfig-2.2.27.tar.gz from server1 to server2. To do this, run

server2:

nc -lp 1234 > ISPConfig-2.2.27.tar.gz

on server2 (1234 is some unused port - you can replace it with another value if you like). server2 will then wait for the file ISPConfig-2.2.27.tar.gz on port 1234.

On server1, run

server1:

nc -w 1 server2.example.com 1234 < ISPConfig-2.2.27.tar.gz

to start the file transfer.

Selected Comments

Maximo Migliari:

More recent versions of the netcat command (nc) will not allow the -p and -l options to be used at the same time, so instead of:

nc -l -p 1234 | dd of=/dev/sda

you would type:

nc -l 1234 | dd of=/dev/sda

If you are using nc with dd to transfer an image of a partition from one machine to the other, one of the problems is that dd and netcat won't show you a progress bar of the operation. One solution to this is to install pipe viewer by Andrew Wood. It then allows you to pipe the netcat command to the pipe viewer, allowing you to view the progress of the entire operation and for debugging.

target machine:

nc -l 1234 | pv | dd of=/dev/sda

source machine:

dd if=/dev/sda | nc 192.168.0.12 1234

[Jul 2, 2008] Linux Configure Netconsole To Log Messages Over UDP Network by Vivek Gite

How do I use nc / netcat instead of messing with syslogd?

This is called one minute configuration. You can easily get output on 192.168.1.100 without using syslogd. All you have to do is run netcat (nc) command, on 192.168.1.100:
$ nc -l -p 30000 -u
Login to any other box, enter command:
# modprobe netconsole [email protected]/eth0,[email protected]/00:19:D1:2A:BA:A8
Output should start to appear on 192.168.1.100 from 192.168.1.5 without configuring syslogd or anything else.

Further readings:

Copy hard disk or partition image to another system using a network and netcat (nc)

Our sample setup

-----------------------
HostA // 192.168.1.1
------------------------
           sda
        NETWORK
           sdb
------------------------
HostB // 192.168.1.2
-------------------------

Your task is copy HostA /dev/sda to HostB's /dev/sdb using netcat command. First login as root user

Command to type on hostB (receiving end ~ write image mode)

You need to open port on hostB using netcat, enter :
# netcat -p 2222 -l |bzip2 -d | dd of=/dev/sdb
Where,

Command to type on hostA (send data over a network ~ read image mode)

Now all you have to do is start copying image. Again login as root and enter:
# bzip2 -c /dev/sda | netcat hostA 2222
OR use IP address:
# bzip2 -c /dev/sda | netcat 192.168.1.1 2222

This process takes its own time.

A note about latest netcat version 1.84-10 and above

If you are using latest nc / netcat version above syntax will generate an error. It is an error to use -l option in conjunction with the -p, -s, or -z options. Additionally, any timeouts specified with the -w option are ignored. So use nc command as follows.

On hostA, enter:
# nc -l 2222 > /dev/sdb
On hostB, enter:
# nc hostA 2222< /dev/sda
OR
# nc 192.168.1.1 2222< /dev/sda

Using a second machine (hostB), connect to the listening nc process at 2222 (hostA), feeding it the file (/dev/sda)which is to be transferred. You can use bzip2 as follows.
On hostA, enter:
# nc -l 2222 | bzip2 -d > /dev/sdb
On hostB, enter:
# bzip2 -c /dev/sda | nc 192.168.1.1 2222

Further readings

How do I improve performance?

As suggested by anonymous user:

You should definitely use bs=16M or something like that. Otherwise, the copy will take forever. Copying a 300 GB hard drive over a 1 Gbps cross-over cable took about 1 1/2 hours or so using bs=16M Without this option, the same thing would have taken about 7 hours.

In short use command as follows:
# netcat -p 2222 -l |bzip2 -d | dd of=/dev/sdb

Netcat – The TCP-IP Swiss Army Knife

Netcat - The TCP/IP Swiss Army Knife
Tom Armstrong
February 15, 2001

Overview

Netcat is a tool that every security professional should be aware of and possibly have in their 'security tool box'. In May/June of 2000, insecure.org conducted a survey of 1200 Nmap users from the Nmap-hackers mailing list to determine their favorite security tools. Netcat was the second most popular tool, not including Nmap. A quick search on securityportal (www.securityportal.com) found 166 matches of netcat. Most of the matches describe or use netcat in some way. Netcat is a utility that is able to write and read data across TCP and UDP network connections. If you are responsible for network or system security it essential that you understand the capabilities of netcat.

Netcat should not be installed unless you have authority to do so. Never install any executable unless you can trust the providor. If possible review the source and compile it yourself. To be safe only use netcat in a test environment.

Hobbit ([email protected]) created netcat in 1995 as a feature-rich network debugging and exploration tool. Its purpose was to be able to create just about any type of network connection. According to Hobbit-

Some of the features of netcat are:

Some of the potential uses of netcat:

The original version of netcat was released to run on Unix and Linux. Weld Pond ([email protected]) released the Windows NT version in 1998. The source code is available for both versions.

Remote command prompt anyone?

On a Windows NT server issue the following command in the directory that contains netcat:

nc -l -p1234 -d -e cmd.exe –L

This –l puts netcat into listen mode, the -p1234 tells netcat to use port 1234, the –d allows netcat to run detached from the console, the –e cmd.exe tells netcat to execute the cmd.exe program when a connection is made, and the –L will restart Netcat with the same command line when the connection is terminated.

On the client system issue the following command:

nc destination 1234

This command causes netcat to connect to the server named destination on port 1234. Immediately you are given a console connection to the destination server. Be careful! To exit the remote console session type:

exit

You will be returned to your own console and will be able to reconnect to the destination server because netcat was started on the destination server with the –L option.

FTP & drive mapping blocked?

To receive a file named newfile on the destination system start netcat with the following command:

nc –l –p 1234 >newfile

On the source system send a file named origfile to the destination system with the following command:

nc destination 1234 <origfile

Issue a ^C on the source system and your done. Be sure to check the file to be sure it is the same size as the original.

Hiding Netcat on Windows NT

Here are a few ways that a hacker could use to hide netcat on a system or use it behind a firewall:

Port Scanning

A scanning example from Hobbit is "nc -v -w 2 -z target 20-30". Netcat will try connecting to every port between 20 and 30 [inclusive] at the target, and will likely inform you about an FTP server, telnet server, and mailer along the way. The -z switch prevents sending any data to a TCP connection and very limited probe data to a UDP connection, and is thus useful as a fast scanning mode just to see what ports the target is listening on. To limit scanning speed if desired, -i will insert a delay between each port probe. Even though netcat can be used for port scanning it isn't its strength. A tool such as nmap is better suited for port scanning.

Netcat + Encryption = Cryptcat

Netcat is a useful tool as it is, but if someone were using it you would be able to at least get a feel for what they were doing. At least you could before Cryptcat! Cryptcat is the standard netcat enhanced with Bruce Schneier's twofish encryption. It can be found at www.farm9.com. Linux, OpenBSD, FreeBSD, and Windows versions are available. So much for sniffing any netcat traffic!

Command Option Overview

Netcat accepts its commands with options first, then the target host, and everything thereafter is interpreted as port names or numbers, or ranges of ports in M-N syntax. Netcat does not currently handle portnames with hyphens.

Option

Description

-d

Allows netcat to detach from the console on Windows NT.

-e

Executes a program if netcat is compiled with the

–DGAPING_SECURITY_HOLE.

-i

Sets the interval time. Netcat uses large 8K reads and writes. This basically sends data one line at a time. This is normally used when data is read from files or pipes.

-g

Used to construct a loose-source-routed path for your connection. This is modeled after "traceroute".

-G

Positions the "hop pointer" within the list.

-l

Forces netcat to listen for an inbound connection. An example "nc –l –p 1234 <filename" tells netcat to listen for a connection on port 1234 and once a connection is made to send the file named filename. The file is sent whether the connecting system wants it or not. If you specify a target host netcat will only accept an bound connection only from that host and if you specify one, only from the specified foreign source port.

-L

Restarts Netcat with the same command line that was used when the connection was started.. This way you can connect over and over to the same Netcat process.

-n

Forces netcat to only accept numeric IP addresses and to not do any DNS lookups for anything

-o

Used to obtain a hex dump file of the data sent either way, use "-o logfile". The dump lines begin with "<" or ">" to respectively indicate "from the net" or "to the net", and contain the total count per direction, and hex or ascii representations of the traffic.

-p

Required for outbound connections. The parameter can be numeric or a name as listed in the services file. If –p is not used netcat will bind to whatever unused port the systems gives it, unless the –r option is used.

-r

Causes port scanning to be done randomly. Normally it is done highest to lowest.

-s

Used to specifiy local network source address. Usage "-s ip-addr" or "-s name".

-t

Enables netcat to respond to telnet option negotiation if netcat is compiled with –DTELNET parameter. Telnet daemons will get no useful answers, as they would from a telnet program.

-u

Tells netcat to use UDP instead of TCP.

-v

Controls the level of verbosity.
  • (without –n) netcat will do a full forward and reverse name and address lookup for the host, and warn you about the all-to-common problem of mismatched names in the DNS.
  • Usually want to use the –w 3, which limits the time spent trying to make a connection.
  • If multiple ports are given –v must be specified twice.

-w

Limits the time spent trying to make a connection.

-z

Prevents sending any data to a TCP connection and very limited probe data to a UDP connection. Use –i to insert a delay between each port probe. This is useful as a fast scanning mode just to see what ports the target is listening on.

Conclusion

Netcat is a powerful tool that every security professional should be familiar with. It should be used with caution. I would not recommend installing netcat on your production networks. I would suggest using it to test your firewall, and router configurations in a test environment. It can also be used to test your operating system lockdown procedures. Be certain that you have the authority to install and use netcat on your network before doing so. You might even want to review the source code to learn how Hobbit built netcat and how Weld Pond ported it to the Windows platform.

References

1. Insecure.org, "Top 50 Security Tools"
URL: http://www.insecure.org/tools.html (August 21, 2000)

2. Hobbit, "New tool available: Netcat"
URL: http://lists.insecure.org/bugtraq/1995/Oct/0028.html (October 28, 1995)

3. Weld Pond, "Netcat 1.10 for NT"
URL: http://www.l0pht.com/~weld/netcat/readment.txt (February 2, 1998)

4. Hobbit, "Netcat 1.10"
URL: http://www.l0pht.com/~weld/netcat/readme.html (March 20, 1996)

5. Farm9, "cryptcat = netcat + encryption"
URL: http://farm9.com/content/Free_Tools/Cryptcat (October 2, 2000)

6. Hobbit, "Netcat 1.10"
URL: http://www.l0pht.com/~weld/netcat/readme.html (March 20, 1996)

Netcat Tutorial The Haskell Sequence

Simple File Transfer

So as an example, I will start two copies of netcat on the same machine locally:

adam@adamp:~$ netcat -l -p 1111

Here, using the -l switch, we are able to specify that netcat should go into listen mode i.e. to listen on
the specified port. Using p 1111 we are able to specify that we are using port 1111. To summarize,
netcat will sit and listen for TCP connections on port 1111 and print any data it receives out to the
screen. In another window we start netcat as:

adam@adamp:~$ netcat 127.0.0.1 1111

This will connect to host 127.0.0.1 (Locally) on port 1111.
We are now able to have a full two way data transmission, in Window 1:

adam@adamp:~$ netcat -l -p 1111This message was typed in WINDOW1. This message was typed in WINDOW2Now I'm going to end communication with ^C (Ctrl-C)
adam@adamp:~$

And in Window 2:

adam@adamp:~$ netcat 127.0.0.1 1111

This message was typed in WINDOW1 This message was typed in WINDOW2 Now I'm going to end communication with ^C (Ctrl-C)
adam@adamp:~$

This is the most basic use of netcat described. Here, we are using a BASH shell, and thus we may pipe |
data to and from netcat, as well as using the redirection (>, >>, <, <<) to allow netcat to integrate into
the shell environment. We will now examine using netcat with one of the redirection operators. Lets
say we wanted to simply transmit a plaintext file. In one window, we will start netcat as:

adam@adamp:~$ netcat -l -p 1111 > outputfile

This will run netcat with the same parameters specified above, except it will redirect
all text received into outputfile.

adam@adamp:~$ echo > infile << EOF
> This is a test file.
> I am going to attempt to transmit this.
> Using Netcat.
> EOF
adam@adamp:~
$

Here, we have created some text in a file, and this is the file we are going to attempt to transmit:

adam@adamp:~$ cat infile | netcat 127.0.0.1 1111 q 10adam@adamp:~$

http://www.learnsecurityonline.com © Learn Security Online, Inc. 2004-2005

Hopefully tbr> $

And here we can confirm that it has. The -q 10 in the command line will quit after EOF (Otherwise
netcat will hang waiting for more input for cat and we will have to terminate it manually). The
parameter 10 causes it to quit after 10 seconds anyway.

Tar

Now, there is no reason why we can't integrate tar and netcat together, and use this to transmit a
directory across a netcat socket:

On one side: tar zcfp - /path/to/directory | nc -w 3 127.0.0.1 1234

The tar statement before the pipe tars and compresses (using gzip) every file within that directory,
before printing its output to stdout (The screen). It is then caught by the pipe, and piped to nc which in
this example, connects to 127.0.0.1 on port 1234 and sends it the data which would normally hit the
screen. The w 3 switch causes nc to allow for a 3 second timeout (In the event of a temporary
disconnection or similar).

On the other side: nc -l -p 1234 | tar xvfpz

This will listen on port 1234 for a connection, and will pass any data received to tar. Using the option v
we can print out filenames to screen:

Simple Socket Reply

With what we have learned so far, we are easily able to get netcat to listen in on a socket, and pump out
any data we wish when it receives a connection.

As an example:

while true; do echo "Leave me alone" | netcat -l -p 1234 w10; done

Consider this line. Firstly lets examine echo "Leave me alone" | netcat -l -p 1234 -w10

What we are doing here, is listening in on port 1234 with a wait time of 10 seconds. If/when we receive
a connection, pipe the results of echo "Leave me alone" to netcat. The w 10 is necessary, as otherwise
any connection made in will remain open forever. We can also optionally add a v in to the netcat
command line which will give us verbose information, i.e. who is connecting.

Every time a connection times out (either with the w 10 command line switch, or because a connection
has been made and then closed), netcat will exit. As this is not what we want, we put the command line
within a standard BASH: while CONDITION; do STATEMENT; done clause, which when the
condition is set to true will run forever.

Inetd

If you build netcat with GAPING_SECURITY_HOLE defined, you can use it as an "inetd" substitute
to test experimental network servers that would otherwise run under "inetd".

A script or program will have its input and output hooked to the network the same way, perhaps sans
some fancier signal handling.

Given that most network services do not bind to a particular local address, whether they are under
"inetd" or not, it is possible for netcat avoid the "address already in use" error by binding to a specific
address.

This lets you [as root, for low ports] place netcat "in the way" of a standard service, since inbound
connections are generally sent to such specifically-bound listeners first and fall back to the ones bound
to "any".

This allows for a one-off experimental simulation of some service, without having to screw around
with inetd.conf. Running with -v turned on and collecting a connection log from standard error is
recommended.

Netcat as well can make an outbound connection and then run a program or script on the originating
end, with input and output connected to the same network port.

This "inverse inetd" capability could enhance the backup-server concept described above or help
facilitate things such as a "network dialback" concept.

The possibilities are many and varied here; if such things are intended as security mechanisms, it may
be best to modify netcat specifically for the purpose instead of wrapping such functions in scripts.

Speaking of inetd, netcat will function perfectly well *under* inetd as a TCP connection redirector for
inbound services, like a "plug-gw" without the authentication step.

This is very useful for doing stuff like redirecting traffic through your firewall out to other places like
web servers and mail hubs, while posing no risk to the firewall machine itself.

Put netcat behind inetd and tcp_wrappers, perhaps thusly:

www stream tcp nowait nobody /etc/tcpd /bin/nc -w 3 realwww 80

and you have a simple and effective "application relay" with access control and logging. Note use of
the wait time as a "safety" in case realwww isn't reachable or the calling user aborts the connection --
otherwise the relay may hang there forever.

Inetd/tcp_wrappers and netcat information, courtesy of: http://www.spyder-fonix.com/netcat.html

Talking to syslogd -r

Syslog Daemons running with the r switch log not only their own hosts data but accept remote UDP
broadcasts. They listen in on UDP port 514.

"echo '<0>message' | nc -w 1 -u loggerhost 514"

If loggerhost is running syslogd r and can accept your messages.

Note the -u switch here, to put netcat into UDP mode. Specifying the <0> before your message ensures
that your message receives top priority within syslog (kern.emerg)

Scanning

The scanning features of netcat can be used against yours or your friends networks to get useful
information about which hosts have certain ports open. You can also send a precompiled data file to
each. For example:

Echo EXIT | nc -w 1 127.0.0.1 20-250 500-600 5990-7000

Will scan 127.0.0.1 on ports 20-250, 500-600 and 5990-7000. Every port that it finds is open, it will
pipe the output of echo "EXIT" being the word "EXIT" to that port.
The results are as follows:

(For the sanity of my server, I have blocked out a number of parts from certain service banners.)
And now with UDP scanning: nc -v -w 1 127.0.0.1 u 20-250 500-600 5990-7000 we receive:

adam@adamp:~$ nc -u -v -w 1 127.0.0.1 20-250 500-600 5990-7000localhost [127.0.0.1] 250 (?) openadam@adamp:~$

-v was to put netcat into verbose mode, and u was telling netcat to fall into UDP mode.

Spoofing

"Your TCP spoofing possibilities are mostly limited to destinations you can source-route to, while
locally bound to your phony address.

Many sites block source-routed packets these days for precisely this reason.

If your kernel does oddball things when sending source-routed packets, try moving the pointer
around with -G. You may also have to fiddle with the routing on your own
machine before you start receiving packets back.

Warning: some machines still send out traffic using the source address of the outbound interface,
regardless of your binding, especially in the case of localhost.

Check first. If you can open a connection but then get no data back from it, the target host is probably
killing the IP options on its end [this is an option inside TCP wrappers and several other packages],
which happens after the 3-way handshake is completed.

If you send some data and observe the "send-q" side of "netstat" for that connection increasing but
never getting sent, that's another symptom. Beware: if Sendmail 8.7.x detects a source-routed SMTP
connection, it extracts the hop list and sticks it in the Received: header!"

http://www.spyder-fonix.com/netcat.html

Spoofing is a useful technique, as is source routing.

Source routing is almost obsolete now, and the majority of routers filter out source routed packets.
Source routing in a nutshell is basically setting the route that the packet will take at the source, and
storing that information along with the packet.

Normally, each router makes its own mind up as to where a packet will get routed, and follows its
predefined routing tables. If we have access to all routers between our device and the target device
(which can be one machine if youre talking about your local LAN server), then we are able to modify
the routing entries on those devices, bind a phoney address to our machine and source route packets to
the intended destination.

Spoofing is where we modify the source address of a packet so that the recipient believes it came from
a different address. There are two problems with this;


A number of clever ISP routers will drop packets with incorrect source addresses.

If the destination host does get to receive your spoofed packet, it will send data back to the
spoofed address (instead of ours). This does have a number of uses however in the example of
ICMP ping flooding a host and spoofing the source address to Microsoft.com (as a theoretical
example).

Simple Response Service

echo -e "GET http://www.google.com HTTP/1.0\n\n" | nc w 5www.google.com 80

We make a connection to google.com on port 80 (Web server port), and put in an HTTP request for
http://www.google.com. At this point, we are presented with the HTML spurted out by the web server.
We can pipe this to "| less" or similar or even our favourite HTML interpreter.

Take a look at this example, and you will see what we have done here. In one instance we have created
an HTML file webfrontend and we now pipe that HTML to any incoming connection to netcat on port
1111.

We then make a connection on the larger window, using lynx http://127.0.0.1:1111 and we have
made ourselves a tiny http server, possibly could be used as a holding page server or something similar.

Advanced Uses

Now we'll set up a server netcat to listen on port 1111. We'll also set up a client netcat to talk to the real
web server on port 81. By getting them to pass all data they receive to each other, together they form a
proxy; something that sits in the middle of a network connection. Here are the commands we use:

mknod backpipe p

nc -l -p 1111 0backpipe

Because bash pipes only carry data in one direction, we need to provide a way to carry the responses as
well. We can create a pipe on the local filesystem to carry the data in the backwards direction with the
mknod command; this only needs to be run once.

Requests coming into the proxy from the client arrive at the first nc, listening on port 1111. They get
handed off to the "tee" command, which logs them to the inflow file, then continue on to the second nc
command which hands them off to the real web server. When a response comes back from the server, it
arrives back at the second nc command, gets logged in the second tee command to the outflow file, and
then gets pushed into the backpipe pipe on the local filesystem. Since the first netcat is listening to that
pipe, these responses get handed to that first netcat, which then dutifully gives them back to the original
client.

While the above example is for watching tcp streams going to and from a web server, the above
technique is useful for watching any tcp connection. In fact, since nc also works with udp packets
something telnet can't do - it should be possible to even set up udp proxies this way.

Windows Command Shell

As we can see from the image above, we have started netcat with options of l p 1234 e
"c:\windows\system32\cmd.exe". These are the same options as with the Unix shell, and this should
theoretically start a cmd.exe shell listening in on port 1234:

As you see from above, this has succeeded. Netcat and program execution for Windows can be used in
exactly the same way.

Unauthorised Proxying

Assume you are an administrator of a Linux router. Using the methods above, as well as your iptables
software, you can proxy a users outgoing connection through your nc proxy. Using iptables with the j
DNAT target and the j REDIRECT target, you can transparently proxy outgoing connections through
to any other ports you want, and what better to use than your nc proxy?

Cryptcat

Cryptcat can be found at: http://sourceforge.net/projects/cryptcat/ and is the ultimate companion for
Netcat. It includes a lightweight version of Netcat, featuring encrypted transport properties. (Just for
those superbly paranoid!). Useful for encrypting communications out of a network.

Final Thoughts

If I was given one tool on a freshly installed PC, I would ask for Netcat. Due to its versatility and its
huge range of uses, it can be used as a transfer tool, a scanning tool, a server, a proxy and so much
more. I have put down everything useful I can think of, and welcome any further suggestions directed
to [email protected]

Command Cheat Sheet

The following are the most useful uses of netcat:

For windows nc d can be used to detach from the console.

nc -l -p [port] will create a simple listening tcp port. Add u to put into UDP mode.
nc -e [program] To redirect stdin/stdout from program.
nc -w [timeout] To set a timeout before netcat automatically quits. (Used within a loop usually)
program | nc To pipe output of program to netcat
nc | program To pipe output of netcat to program
nc -h Help sheet
nc -v To put into verbose mode, or use v v to put into ultra-verbose mode!
nc -g or nc G Source routing flags
nc -t Use telnet negotiation (If performing telnet negotiation)
.
nc -o [file] Hex dump traffic to file
nc -z No I/O (Used for scanning ports)

Play with the Lovely Netcat LG #74 By zhaoway

Netcat is a featured networking utility which reads and writes data across network connections, using the TCP/IP protocol. It is designed to be a reliable "back-end" tool that can be used directly or easily driven by other programs and scripts. At the same time, it is a feature-rich network debugging and exploration tool, since it can create almost any kind of connection you would need and has several interesting built-in capabilities.

It provides access to the following main features:

netcat could forward data stream from stdin to a TCP or UDP socket, and from a TCP or UDP socket to stdout. Just like the cat program to forward data from stdin to stdout. According to unconfirmed sources, that's the origin of the netcat program name.

/usr/bin/yes generates stream of y

zw@q ~ % yes
y
y
y
y
y
y
y

Press ctrl-C to stop the y's. You can generated stream on no too.

zw@q ~ % yes no
no
no
no
no
no

The hub (hub.c) and cable (cable.c) utilities are certainly inspired by netcat which could forward data stream from a socket to stdout, and from stdin to a socket. Did I forget to recommend the netcat companion documentation for you to read? ;-) Hub is designed to be like a server, and cable is designed to be like a client. Instead of forwarding data between stdin/stdout and a socket, hub and cable forward and multiplex data from a socket to any other sockets. That's where the names come from. They're just like Ethernet hub and cable. Lets' see a screenshot. Yeah, screenshot! ;-)

zw@q ~ % ./hub
lullaby internetworks lab: (server alike) hub $Revision: 1.2 $
Copyright (C) 2001  zhaoway <[email protected]>

Usage: hub [hub buffer size] [tcp port number] [number of hub ports]

o hub buffer size is in bytes. for example 10240.
o tcp port number is at least 1024 so i do not need to be root.
o number of hub ports is at least 2. happy.
zw@q ~ %

Hub will listen on a TCP port simulating a many port Ethernet hub. Data come in from one hub port will be forwarded to other hub ports. You could test the hub alone without cable using netcat. Note: nc is the acronym for netcat.

  1. Launch hub in the console A: ConA % ./hub 10240 10000 2
  2. From console B, connect a netcat: ConB % nc localhost 10000
  3. From console C, connect another netcat: ConC % nc localhost 10000
  4. Then you could type in ConC and read the output in ConB, vice versa.

Then there is cable:

zw@q ~ % ./cable
lullaby internetworks lab: (client alike) cable $Revision: 1.2 $
Copyright (C) 2001  zhaoway <[email protected]>

Usage: cable [cable buffer size] [1st ip] [1st port] [2nd ip] [2nd port] ..

o cable buffer size is in bytes. for example 10240.
o ports should be listening or connection attempts will fail.
o number of ip addr and port pairs is at least 2.
zw@q ~ %

Cable is more or less like a shared Ethernet bus coaxial cable. It forwards and multiplexes data between listening socket daemons. Let's test it too.

  1. Launch a netcat daemon in ConA: ConA % nc -l -p 10000
  2. Launch another netcat daemon in ConB: ConB % nc -l -p 10001
  3. Arrange the cable: ConC % ./cable 10240 127.0.0.1 10000 127.0.0.1 10001
  4. Then you could type in ConA and read the output from ConB, vice versa.

There are some interesting techniques used in developing hub and cable. Notably the select() function call. But for now, we will focus on our course to reinvent the /usr/bin/yes first. ;-)

It's not a very easy task to reinvent /usr/bin/yes using netcat and hub and cable. I could only give a cheat answer. And that's why I need to set the buffer size command line argument. But anyway, let's begin!

The main idea is as following. First we set up a three-port hub, then we using cable to connect two hub port together, after that we could using netcat to echo any character into the remain free hub port. It's like the following diagram:

            |            cable
           \|/        ,---------,
            |         |         |
            V         V         V
	,--[ ]-------[ ]-------[ ]--.
        |   A         B         C   |
        |       three-port hub      |
	`---------------------------'

Because the nature of the hub, data sent in from port A, will be forwarded to port B and port C, since port B and C are connected by a cable, the data come out of the hub will go right back in, and then being multiplexed and forwarded to port A and circulating in the cable loop to eternity. Eventually port A will receive infinite copies of the original data sent in.

Lets' construct the device.

  1. In ConA, we launch the three-port hub: ConA % ./hub 10240 10000 3
  2. In ConB, we loop the cable: ConB % ./cable 10240 127.0.0.1 10000 127.0.0.1 10000

Now after we finished construction of our device, then we will using netcat to finally finish our reinvention of /usr/bin/yes.

ConC % echo "y" | nc localhost 10000

The tricky exercises left for the reader is: what if we change the buffer size of both cable and hub from 10240 to 1? You could try and see for yourself.

Have fun and good luck!

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

Socat

Reference



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: June, 28, 2020