0

IP address of CLIENT is in this $VAR:

VAR=$(nc -v -l 80 2>&1)

I can further refine it.

How to send this $VAR back to the client
without running another netcat command ?

With other programming languages..
IP can be obtained prior to sending a response.
and thus can be included in the response.

Not possible with netcat ?

2 Answers 2

4

Of course it's possible. Just set up nc as a co-process:

#!/bin/bash -x

# Greets the client with their hostname.

coproc ( nc -l -v localhost 3000 2>&1 )

{
    declare "$( sed -e 's/^Connection from \([^ ]*\).*$/client="\1"/' -e 'q' )"
    printf 'Hello there, user on %s\n' "$client"
} <&${COPROC[0]} >&${COPROC[1]}

kill "$COPROC_PID"

For something more advanced, like handling HTTP requests:

#!/bin/bash

# Handles one request, then kills nc and restarts

while true; do
    coproc ( nc -l localhost 3000 2>&1 )

    {
      get_http_request_header
      process_request
      send_http_reply
    } <&${COPROC[0]} >&${COPROC[1]}

    kill "$COPROC_PID"
done  

The commands get_http_request_header, process_request, and send_http_reply may be shell functions or separate scripts that you write.

The get_http_request_header routine would get its standard input from the client connected to nc and would parse the request, possibly storing it in a temporary file or setting some global variables or in some other way passing the needed information to process_request.

process_request may handle compiling the result in whatever way is necessary.

send_http_reply would print to the client by simply writing to standard output.

Another possible setup where the information on the server side is simply passed along the internal steps through pipes:

#!/bin/bash

# Handles one request, then kills nc and restarts

while true; do
    coproc ( nc -l localhost 3000 2>&1 )

    {
      get_http_request_header |
      process_request |
      send_http_reply
    } <&${COPROC[0]} >&${COPROC[1]}

    kill "$COPROC_PID"
done  
0

This question was already answered or whereabouts in display-welcome-message-upon-successful-netcat-connection

But essentially, you'll do as follows with your listener:

(echo "$VAR"; cat) |nc -nvlp 4444

When your client connects, the listener echoes this variable onto the client's stdout.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .