これは、なにをしたくて書いたもの?
socatでTCP Echoサーバーを立てる方法をメモしておきます。
以前書いたエントリー内でも少し使ったことがあるのですが、単体のエントリーとして書いてあった方が個人的には便利かなと思ったので。
環境
今回の環境はこちら。
$ socat -V socat by Gerhard Rieger and contributors - see www.dest-unreach.org socat version 1.8.0.0 on 08 Apr 2024 14:50:22 running on Linux version #71-Ubuntu SMP PREEMPT_DYNAMIC Tue Jul 22 16:52:38 UTC 2025, release 6.8.0-71-generic, machine x86_64 features: #define WITH_HELP 1 #define WITH_STATS 1 #define WITH_STDIO 1 #define WITH_FDNUM 1 #define WITH_FILE 1 #define WITH_CREAT 1 #define WITH_GOPEN 1 #define WITH_TERMIOS 1 #define WITH_PIPE 1 #define WITH_SOCKETPAIR 1 #define WITH_UNIX 1 #define WITH_ABSTRACT_UNIXSOCKET 1 #define WITH_IP4 1 #define WITH_IP6 1 #define WITH_RAWIP 1 #define WITH_GENERICSOCKET 1 #define WITH_INTERFACE 1 #define WITH_TCP 1 #define WITH_UDP 1 #define WITH_SCTP 1 #define WITH_DCCP 1 #define WITH_UDPLITE 1 #define WITH_LISTEN 1 #define WITH_POSIXMQ 1 #define WITH_SOCKS4 1 #define WITH_SOCKS4A 1 #define WITH_SOCKS5 1 #define WITH_VSOCK 1 #define WITH_NAMESPACES 1 #define WITH_PROXY 1 #define WITH_SYSTEM 1 #define WITH_SHELL 1 #define WITH_EXEC 1 #undef WITH_READLINE #define WITH_TUN 1 #define WITH_PTY 1 #define WITH_OPENSSL 1 #undef WITH_FIPS #define WITH_LIBWRAP 1 #define WITH_SYCLS 1 #define WITH_FILAN 1 #define WITH_RETRY 1 #define WITH_MSGLEVEL 0 /*debug*/ #define WITH_DEFAULT_IPV 0
OSはUbuntu Linux 24.04 LTSです。
$ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 24.04.3 LTS Release: 24.04 Codename: noble $ uname -srvmpio Linux 6.8.0-71-generic #71-Ubuntu SMP PREEMPT_DYNAMIC Tue Jul 22 16:52:38 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
またこのサーバーは192.168.33.11で動作しているものとします。
socatでTCP Echoサーバーを立てる
socatで簡単にTCP Echoサーバーを立てるには、catコマンドを使うのが簡単です。
$ socat tcp-listen:5000,fork,reuseaddr exec:cat ## もしくはこちら $ socat tcp-listen:5000,fork,reuseaddr system:cat
socatのexec:
ではコマンドを指定でき、system:
ではシェルを経由してコマンドを実行できます。
Ubuntu Manpage: socat - Multipurpose relay (SOcket CAT)
こちらを使って接続を受け付けた後にcatで入力値を返すようにしています。
確認。
$ curl telnet://192.168.33.11:5000 hello world hello world foo foo bar bar
OKですね。
この間、socat側は無言なのですが、以下のように-v
オプションをつけるとデータ転送の様子が標準エラー出力に書き出されるようになります。
$ socat -v tcp-listen:5000,fork,reuseaddr exec:cat > 2025/08/17 13:30:25.000020267 length=12 from=0 to=11 hello world < 2025/08/17 13:30:25.000020834 length=12 from=0 to=11 hello world > 2025/08/17 13:30:25.000992663 length=4 from=12 to=15 foo < 2025/08/17 13:30:25.000992883 length=4 from=12 to=15 foo > 2025/08/17 13:30:28.000833428 length=4 from=16 to=19 bar < 2025/08/17 13:30:28.000833635 length=4 from=16 to=19 bar
こんなところで。