Linux shell脚本中发起tcp、udp连接

本文介绍如何使用Linux系统中的/dev/tcp和/dev/udp设备文件,直接从shell脚本发起TCP和UDP连接,提供了一种方便高效的网络测试方法。通过具体的示例,展示了如何建立连接、发送消息及关闭连接。

发个好玩的东东。

通过/dev/tcp、/dev/udp可以直接在shell脚本中发起tcp、udp连接,方便又高效,平时用于测试啥的还是挺方便的。

先看下bash man里面的介绍,

/dev/tcp/host/port
	 If host is a valid hostname or Internet address, and port is
	 an integer port number or service  name,  bash  attempts  to
	 open a TCP connection to the corresponding socket.
/dev/udp/host/port
	 If host is a valid hostname or Internet address, and port is
	 an integer port number or service  name,  bash  attempts  to
	 open a UDP connection to the corresponding socket.

接下来,我们实操一下。在一台机器运行服务端程序,打印客户端消息,具体代码参考:基于TCP通信的简单服务端和客户端程序

另一端使用上述方法发起tcp连接,并发送消息,
在这里插入图片描述

可见,可使用以下shell命令发起tcp连接,

exec 9>/dev/tcp/192.168.0.136/5000

其中9为执行的文件描述符。这里>重定向符表示该文件描述符只能写入,如果想读取,可使用一下命令,

exec 9<>/dev/tcp/192.168.52.136/5000

至于关闭连接,则通过以下命令,

exec 9>&-

其中,9代表刚才创建的描述符。

关于 >&-的解释,可以参考bash的man手册的REDIRECTION章节,

REDIRECTION
	   ...
       Each redirection that may be preceded by a file descriptor number may instead be preceded
       by  a word of the form {varname}.  In this case, for each redirection operator except >&-
       and <&-, the shell will allocate a file descriptor greater than 10 and assign it to  var‐
       name.   If  >&-  or  <&-  is preceded by {varname}, the value of varname defines the file
       descriptor to close.

因此,也可以用以下命令关闭连接,

exec 9<&-
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值