Netcat – socket in time_wait when echoing and piping, but not when invoked directly

I’m testing an application using netcat (nc) and I’m getting very low throughput on network connections. When I ran netstat -tnpo I see numerous TCP sessions in TIME_WAIT. I’m sending data to my application via a bash script as indicated below:

while true; do
    echo "<required string>" | nc server_ip port
done

If I instead do this at the terminal:

nc server_ip port
<required string>

the connection terminates immediately and there is no TCP session left in TIME_WAIT.

Why the difference? What do I need to do differently to ensure that after each echo, no TCP port is left in TIME_WAIT?

Answer

You may want to use it like this.

    while true; do
        echo "<required string>" | nc server_ip port < /dev/null   
    done

Apologies I don’t have enough repo to post it like a comment.

Attribution
Source : Link , Question Author : AnthonyK , Answer Author : tollboy

Leave a Comment