检查插座是否在bash中关闭?

Dav*_*rks 6 sockets linux bash shell

我有一个指向套接字的文件描述符(下面的示例代码).

exec 3<>/dev/tcp/localhost/9999
echo -e "Some Command\n" >&3
Run Code Online (Sandbox Code Playgroud)

有时该套接字关闭并需要重新打开(重新启动服务器).

如何测试套接字(在这种情况下为fd#3)是否可写?

无论套接字是否已经关闭,回声总是会成功.

bba*_*a42 4

解决方案是服务器的反馈。

当您向服务器发送请求时,服务器需要做出答复。

exec 3<>/dev/tcp/localhost/9999
echo -e "Some Command\n" >&3
sleep 5 # example max time given to server to respond
cat <&3 #receive an answer
check is correct, restart server otherwise
Run Code Online (Sandbox Code Playgroud)

编辑:使用 netcat 确定端口是否打开

netcat -w 3 -z www.google.com 80
if[ $? -eq 0 ]
then
    echo port open
else
    echo port closed
fi
Run Code Online (Sandbox Code Playgroud)