大网数据广告活动
服务器运维问答

How to automatically close netcat connection after data is sent?

· 52CE 我爱测

I am executing the following command from a script: echo '{"hostUp": true}' | sudo /usr/local/bin/netcat localhost 8001 However, the netcat client stays open indefinitely. How can I close the connection once this data has been se…

问题原文

原帖链接 · Justin Meltzer · CC BY-SA 4.0

I am executing the following command from a script:

echo '{"hostUp": true}' | sudo /usr/local/bin/netcat localhost 8001

However, the netcat client stays open indefinitely. How can I close the connection once this data has been sent?

社区高分解答

原帖链接 · 7yl4r · CC BY-SA 3.0

Both other answers -c and -q given are correct in the right context, but it may help to summarize why there are multiple answers and give a more general solution.

These different options do the same thing but are different implementations of netcat:

  • -c GNU implementation of netcat
  • -q OpenBSD implementation of netcat.
  • -w (other?) OpenBSD implementation of netcat.

Some versions require an int to specify the number of seconds to wait before quitting for the -q and -w options. This int must be > 0 or >= 0, depending on the version.

If you are implementing something across multiple machines and are not sure they use the same implementation of netcat, you might consider wrapping your netcat call with the timeout program to kill netcat after a few seconds.

timeout 5 echo '{"hostUp": true}' | netcat localhost 8001

This approach is a bit clumsy because it puts an upper limit on the execution of netcat regardless of whether or not if it is sending data successfully, but if you are sending a small amount of data and have a few seconds to spare then this should work with any netcat implementation.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2013-06-03)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0 / CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。