You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为socat转发的数据添加前缀与后缀字符串?

实现socat端口转发时添加自定义头尾字符串

Absolutely, this is totally achievable with socat by leveraging its exec option to pipe incoming data through a lightweight processing script. Below are a few reliable approaches tailored to your needs:

基础Bash脚本方案

This uses a simple bash loop to read each line, wrap it with your specified header and footer, and send it onward.

socat tcp-listen:8000,reuseaddr,fork,crnl exec:'bash -c "while IFS= read -r line; do printf \"start,%s,end\r\n\" \"$line\"; done"',pty

关键参数解释

  • crnl: Tells socat to convert incoming CR/LF line endings to LF for the script, and convert outgoing LF back to CR/LF when sending data. This ensures consistent line handling across different systems.
  • IFS= read -r line: Prevents the shell from trimming leading/trailing whitespace and correctly interprets backslashes in input lines.
  • printf \"start,%s,end\r\n\" \"$line\": Explicitly outputs the wrapped line with a CR/LF ending to match your requirement.

更高效的Awk方案

If you're expecting higher throughput or just prefer a more concise command, awk is a better choice for text processing tasks like this:

socat tcp-listen:8000,reuseaddr,fork,crnl exec:'awk "{printf \"start,%s,end\r\n\", \$0}"',pty

Awk is optimized for line-by-line text processing, so it'll handle larger volumes of data more efficiently than a bash loop.

验证效果

When a client sends ABC<CR/LF> to port 8000, socat will forward start,ABC,end<CR/LF> to localhost:9000 exactly as you requested.


内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 23:37:48