How to close netcat connection after receive a server response?
Asked Answered
C

2

8

I need to sendo a lot of messages via netcat or something similar. The problem is that when I run echo "something" | netcat ip port the connection continues opened after I received the response. Actually the connection continues opened waiting for a new input. However, what I need is that the connection closed after I receive the response. Look, my script is basically this:

#!/bin/bash
i=1
while [ $i -ne 10000 ];do
    sed -n $[i]p wordlist | netcat localhost 30002 >> result
    i=$[$i+1]
done

If I can close the connection after print the response in result, everything will work fine. I know that there is an option -w "x" that closes the connection after "x" seconds, but the minimum value for "x" is 1 and 1 is bigger than I can wait, I need close the connection as soon as possible.

Colleen answered 18/1, 2019 at 14:27 Comment(0)
S
4

Unfortunately, the -q flag didn't work for me. I'm using "OpenBSD netcat (Debian patchlevel 1.187-1ubuntu0.1)" and, even though the -q flag shows up in the manual, it didn't work as mentioned in cnicutar's answer.

Therefore, my workaround was:

#!/bin/sh

# POSIX COMPLIANT

HOST="localhost"
PORT=30002

scan () {
    # Ensuring there is no file named msg
    rm msg

    # While msg file doesn't exist or is empty, do
    while [ ! -s msg ]; do
        # Remove instruction from within the loop
        rm msg

        # Append the received messages to msg file, and put the process in the background
        echo "$HOST $PORT" | xargs nc >> msg &

        # If the file exists and is not empty, return, we received the message
        [ -s msg ] && return;

        # A small timeout.. doing some tests I noticed that a timeout of zero sometimes didn't work to catch the message
        # Maybe nc needs a small time to receive everything. You might want to test and increase or decrease this timeout if needed.
        sleep 0.1

        # This script will be spawning a lot of nc process, to kill it before the loop runs again
        pkill -x nc
    done
} 2> /dev/null 

scan

# The function returned, so cat the file
cat msg

# make sure nc is killed
pkill -x nc > /dev/null 2>&1
rm msg
Sofar answered 27/1, 2020 at 16:59 Comment(1)
Amazing answer. Exactly what I was looking for.Smoothtongued
M
1

What you're looking for is the -q switch. If you specify:

netcat -q 0 localhost 30002

netcat will exit immediately.

Mandimandible answered 3/2, 2019 at 21:35 Comment(1)
This is not available in netcat v7.50Jughead

© 2022 - 2024 — McMap. All rights reserved.