How to send only one UDP packet with netcat?

廉价感情. 提交于 2019-12-04 07:25:39

问题


I want to send only one short value in a UDP packet, but running the command

echo -n "hello" | nc -4u localhost 8000

I can see that the server is getting the hello stuff but I have to press Ctrl+c to quit the netcat command.

How can I make it quit after sending hello?


Sorry, for the noise, I re-read the man page and found the -q option.

 echo -n "hello" | nc -4u -q1 localhost 8000

works (it quits after 1 second).

For some reason it does not work with -q0.


回答1:


If you are using bash, you might as well write

echo -n "hello" >/dev/udp/localhost/8000

and avoid all the idiosyncrasies and incompatibilities of netcat.

This also works sending to other hosts, ex:

echo -n "hello" >/dev/udp/remotehost/8000

These are not "real" devices on the file system, but bash "special" aliases. There is additional information in the Bash Manual.




回答2:


I did not find the -q1 option on my netcat. Instead I used the -w1 option. Below is the bash script I did to send an udp packet to any host and port:

#!/bin/bash

def_host=localhost
def_port=43211

HOST=${2:-$def_host}
PORT=${3:-$def_port}

echo -n "$1" | nc -4u -w1 $HOST $PORT



回答3:


On a current netcat (v0.7.1) you have a -c switch:

-c, --close                close connection on EOF from stdin

Hence,

echo "hi" | nc -cu localhost 8000

should do the trick.




回答4:


Netcat sends one packet per newline. So you're fine. If you do anything more complex then you might need something else.

I was fooling around with Wireshark when I realized this. Don't know if it helps.




回答5:


I had the same problem but I use -w 0 option to send only one packet and quit. You should use this command :

echo -n "hello" | nc -4u -w0 localhost 8000


来源:https://stackoverflow.com/questions/9696129/how-to-send-only-one-udp-packet-with-netcat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!