13

I have two virtual machines open, one is listening on the connection, the other connects with nc <ip> <port> from a python subprocess call. I want to send just 1 line of text over the connection then close it. I know how to send a file cat cat <file> | nc <ip> <port> but how can I just send a line of text in the nc command (without using files)?

Crizly
  • 971
  • 1
  • 12
  • 33

4 Answers4

24

Try this:

echo -n 'Line of text' | nc <ip> <port>

You can also use temp file syntax:

cat <(echo "Line of test") | nc <ip> <port>
cb0
  • 8,415
  • 9
  • 52
  • 80
  • With `cat | nc -vl localhost` you can make netcat send data to the client from standard in, your keyboard for example. This works after the connection was established with the client. – Matthias Braun Jun 15 '22 at 15:07
3

The temp file syntax shown by @cb0 could also be used as:

nc <ip> <port> <( echo "Line of text" )

without having to use cat command. This would create a temporary file with the content "Line of text" and then redirect it to the netcat command.

1

Create file test.txt, content of file is 1

netcat [ip-address] [port] <test.txt

At destination you must have something to listen to this.

Manjunath Raddi
  • 421
  • 6
  • 15
0

-N flag is required to exit nc after a message is sent for some servers:

echo "text" | nc -N <ip> <port>

-N shutdown(2) the network socket after EOF on the input. Some servers require this to finish their work.

-- man nc

angordeyev
  • 511
  • 3
  • 11