socat(1)
socat(1) ๐
okay bestie, welcome to the socat(1) manual page. It's giving Multipurpose relay (SOcket CAT), and yes, she's iconic. Let's get into it.
โจ NAME โจ
socat - Multipurpose relay (SOcket CAT)
๐ธ SYNOPSIS ๐ธ
socat [options] <address> <address>
socat -V
socat -h[h[h]] | -?[?[?]]
filan
procan
๐ DESCRIPTION ๐
okay so socat is a command line based utility that establishes two bidirectional byte streams and transfers data between them. Because the streams can be constructed from a large set of different types of data sinks and sources (see address types), and because lots of address options may be applied to the streams, socat can be used for many different purposes.
Filan is a utility that prints information about its active file descriptors to stdout. It has been written for debugging socat, but might be useful for other purposes too. Use the -h option to find more infos.
Procan is a utility that prints information about process parameters to stdout. It has been written to better understand some UNIX process properties and for debugging socat, but might be useful for other purposes too.
The life cycle of a socat instance typically consists of four phases.
In the init phase, the command line options are parsed and logging is initialized.
During the open phase, socat opens the first address and afterwards the second address. These steps are usually blocking; thus, especially for complex address types like socks, connection requests or authentication dialogs must be completed before the next step is started.
In the transfer phase, socat watches both streamsโ read and write file descriptors via select(), and, when data is available on one side and can be written to the other side, socat reads it, performs newline character conversions if required, and writes the data to the write file descriptor of the other stream, then continues waiting for more data in both directions.
When one of the streams effectively reaches EOF, the closing phase begins. Socat transfers the EOF condition to the other stream, i.e. tries to shutdown only its write stream, giving it a chance to terminate gracefully. For a defined time socat continues to transfer data in the other direction, but then closes all remaining channels and terminates.
๐ OPTIONS ๐
Socat provides some command line options that modify the behaviour of the program. They have nothing to do with so called address options that are used as parts of address specifications.
-Vโ Print version and available feature information to stdout, and exit. slay, version check, then bye ๐-h|-?โ Print a help text to stdout describing command line options and available address types, and exit.-hh|-??โ Like-h, plus a list of the short names of all available address options. Some options are platform dependent, so this output is helpful for checking the particular implementation.-hhh|-???โ Like-hh, plus a list of all available address option names.-dโ Without this option, only fatal, error, and warning messages are printed; applying this option also prints notice messages. See DIAGNOSTICS for more information.-d0โ With this option, only fatal and error messages are printed; this restores the behaviour of socat up to version 1.7.4.-d -d|-dd|-d2โ Prints fatal, error, warning, and notice messages.-d -d -d|-ddd|-d3โ Prints fatal, error, warning, notice, and info messages.-d -d -d -d|-dddd|-d4โ Prints fatal, error, warning, notice, info, and debug messages.-Dโ Logs information about file descriptors before starting the transfer phase.--experimentalโ New features that are not well tested or are subject to change in the future must be explicitly enabled using this option.-ly[<facility>]โ Writes messages to syslog instead of stderr; severity as defined with-doption. With optional<facility>, the syslog type can be selected, default is"daemon". Third party libraries might not obey this option.-lf <logfile>โ Writes messages to<logfile>[filename] instead of stderr. Some third party libraries, in particularlibwrap, might not obey this option.-lsโ Writes messages to stderr (this is the default). Some third party libraries might not obey this option, in particularlibwrapappears to only log to syslog.-lp<progname>โ Overrides the program name printed in error messages and used for constructing environment variable names.-luโ Extends the timestamp of error messages to microsecond resolution. Does not work when logging to syslog.-lm[<facility>]โ Mixed log mode. During startup messages are printed to stderr; whensocatstarts the transfer phase loop or daemon mode (i.e. after opening all streams and before starting data transfer, or, with listening sockets withforkoption, before the firstacceptcall), it switches logging to syslog. With optional<facility>, the syslog type can be selected, default is"daemon".-lhโ Adds hostname to log messages. Uses the value from environment variableHOSTNAMEor the value retrieved withuname()ifHOSTNAMEis not set.-vโ Writes the transferred data not only to their target streams, but also to stderr. The output format is text with some conversions for readability, and prefixed with"> "or"< "indicating flow directions.-xโ Writes the transferred data not only to their target streams, but also to stderr. The output format is hexadecimal, prefixed with"> "or"< "indicating flow directions. Can be combined with-v.-r <file>โ Dumps the raw (binary) data flowing from left to right address to the given file. The file name may contain references to environment variables and$$(pid),$PROGNAME(see option option-lp),$TIMESTAMP(uses format%Y%m%dT%H%M%S), andMICROS(microseconds of daytime). These references have to be protected from shell expansion of course.-R <file>โ Dumps the raw (binary) data flowing from right to left address to the given file. See option-rfor customization of file name.-b<size>โ Sets the data transfer block<size>[size_t]. At most<size>bytes are transferred per step. Default is8192bytes.-sโ By default, socat terminates when an error occurred to prevent the process from running when some option could not be applied. With this option, socat is sloppy with errors and tries to continue. Even with this option, socat will exit on fatals, and will abort connection attempts when security checks failed.-S<signals-bitmap>โ Changes the set of signals that are caught by socat just for printing an log message. This catching is useful to get the information about the signal into socats log, but prevents core dump or other standard actions. The default set of these signals isSIGHUP,SIGINT,SIGQUIT,SIGILL,SIGABRT,SIGBUS,SIGFPE,SIGSEGV, andSIGTERM; replace this set (0x89deon Linux) with a bitmap (e.g.,SIGFPEhas value8and its bit is0x0080). Note: SignalsSIGHUP,SIGINT,SIGQUIT,SIGUSR1,SIGPIPE,SIGALRM,SIGTERM, andSIGCHLDmay be handled specially anyway.-t<timeout>โ When one channel has reached EOF (that is not ignored through option(ignoreoef, the write part of the other channel is shut down. Then, socat waits<timeout>[timeval] seconds before terminating. When during the timeout interval the read part of that other channel gives EOF, socat terminates without awaiting the timeout. Default is0.5seconds,0is valid. This timeout is only useful with addresses where write and read part can be closed or shut down independently.-T<timeout>โ Total inactivity timeout: when socat is already in the transfer loop and nothing has happened for<timeout>[timeval] seconds (no data arrived, no interrupt occurred...) then it terminates. Up to version1.8.0.0"0"meant"infinite"; since version1.8.0.1"0"means0and values<0mean infinite, default is-1. Useful with protocols like UDP that cannot transfer EOF.-uโ Uses unidirectional mode. The first address is only used for reading, and the second address is only used for writing (example).-Uโ Uses unidirectional mode in reverse direction. The first address is only used for writing, and the second address is only used for reading.-gโ During address option parsing, donโt check if the option is considered useful in the given address environment. Use it if you want to force, e.g., appliance of a socket option to a serial device.-L<lockfile>โ If lockfile exists, exits with error. If lockfile does not exist, creates it and continues, unlinks lockfile on exit.-W<lockfile>โ If lockfile exists, waits until it disappears. When lockfile does not exist, creates it and continues, unlinks lockfile on exit.-4โ Use IP version 4 in case the addresses do not implicitly or explicitly specify a version. Since version1.8.0.1this is the default.-6โ Use IP version 6 in case the addresses do not implicitly or explicitly specify a version.-0โ Do not prefer a particular IP version; this lets passive addresses (LISTEN,RECV, ...) serve both versions on some platforms (not BSD).--statisticsโ ๐-Sโ Logs transfer statistics (bytes and blocks counters for both directions) before terminating socat. See also signalUSR1.
โจ ADDRESS SPECIFICATIONS โจ
okay so bestie, this is where you tell socat what to talk to ๐ With the address command line arguments, you're basically handing socat instructions plus every lil detail it needs to set up those byte streams. Think of it as giving your bestie the address AND the vibe.
An address specification usually goes like this: an address type keyword, then zero or more required address parameters (separated by : from the keyword and from each other), then zero or more address options (separated by ,). Iconic structure, honestly.
- The keyword tells socat the address type (like
TCP4,OPEN,EXEC). Some keywords have synonyms โ-forSTDIO,TCPforTCP4. Keywords are case insensitive, so don't stress about caps ๐ซถ - For a few special address types, you can just... skip the keyword entirely: address specifications that start with a number get assumed to be
FD(raw file descriptor) addresses, and if there's a/before the first:or,, socat assumesGOPEN(generic file open). Sneaky but slay.
The required number and type of address parameters depend on the address type. Like, TCP4 needs a server specification (name or address) and a port specification (number or service name). No skipping steps, bestie.
Zero or more address options can come along with each address, and they influence the address in various ways. Options are either an option keyword, or an option keyword + a value separated by =. Option keywords are case insensitive too. Now, for filtering which options actually make sense with an address type: every option is a member of one option group, and each address type allows a set of option groups. Only options belonging to one of those allowed groups may be used (except with option -g, which is the chaotic free pass).
Address specifications that follow that whole schema are also called single address specifications. And here's the fun part: two single addresses can be combined with !! to form a dual type address for one channel ๐ In that case, the first address is what socat uses for reading data, and the second address is for writing data. And no, there is no way to specify an option only once so it applies to both single addresses. Sorry bestie, you gotta write it twice.
Usually, addresses are opened in read/write mode. But when an address is part of a dual address specification, or when option -u or -U is used, an address might be used only for reading or only for writing. This detail matters a LOT with some address types, so keep it in mind fr fr.
With socat version 1.5.0 and higher, the lexical analysis tries to handle quotes and parenthesis meaningfully and allows escaping of special characters. If one of the characters (, {, [, ' is found, the corresponding closing character โ ), }, ], ' โ is looked for; and they may also be nested ๐ธ Within these constructs, socat's special characters and strings :, ,, !! are not handled specially. All those characters and strings can be escaped with \ or within "". Protection era ๐
๐ ADDRESS TYPES ๐
This section describes the available address types with their keywords, parameters, and semantics. Buckle up, there's a lot of them and they're all lowkey iconic.
CREATE:<filename>
Opens <filename> with creat() and uses the file descriptor for writing. This is a write-only address because a file opened with creat cannot be read from. See options -u and -U, and dual addresses.
Flags like O_LARGEFILE cannot be applied. If you need them, use OPEN with options create,create instead.
<filename> must be a valid existing or not existing path. If <filename> is a named pipe, creat() might block; if <filename> refers to a socket, that's an error ๐ญ
- Option groups:
FD,REG,NAMED - Useful options:
mode,mode,user,group,unlink-early,unlink-late,append - See also:
OPEN,GOPEN
DCCP-CONNECT:<host>:<port> (DCCP:<host>:<port>)
Establishes a DCCP connect to the specified <host> [IP address] and <port> [DCCP service] using IP version 4 or 6 depending on address specification, name resolution, or option pf.
- Option groups:
FD,SOCKET,IP4,IP6,SCTP,CHILD,RETRY - Useful options:
bind,connect-timeout,tos,dccp-set-ccid,nonblock,sourceport,retry,readbytes - See also:
DCCP4-CONNECT,DCCP6-CONNECT,DCCP-LISTEN,TCP-CONNECT,SCTP-CONNECT
DCCP4-CONNECT:<host>:<port> (DCCP4:<host>:<port>)
Like DCCP-CONNECT, but only supports IPv4 protocol.
- Option groups:
FD,SOCKET,IP4,DCCP,CHILD,RETRY
DCCP6-CONNECT:<host>:<port> (DCCP6:<host>:<port>)
Like DCCP-CONNECT, but only supports IPv6 protocol.
- Option groups:
FD,SOCKET,IP6,DCCP,CHILD,RETRY
DCCP-LISTEN:<port> (DCCP-L:<port>)
Listens on <port> [DCCP service] and accepts a DCCP connection. The IP version is 4, or the one specified with address option pf, socat option (-4, -6), or environment variable SOCAT_DEFAULT_LISTEN_IP. Heads up: opening this address usually blocks until a client connects โ so don't be surprised when it just sits there, that's the vibe.
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP4,IP6,DCCP,RETRY - Useful options:
fork,bind,range,max-children,backlog,accept-timeout,dccp-set-sid,su,reuseaddr,retry - See also:
DCCP4-LISTEN,DCCP6-LISTEN,TCP-LISTEN,SCTP-LISTEN,DCCP-CONNECT
DCCP4-LISTEN:<port> (DCCP4-L:<port>)
Like DCCP-LISTEN, but only supports IPv4 protocol.
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP4,DCCP,RETRY
DCCP6-LISTEN:<port> (DCCP6-L:<port>)
Like DCCP-LISTEN, but only supports IPv6 protocol.
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP6,DCCP,RETRY
EXEC:<command-line>
Forks a sub process that establishes communication with its parent process and invokes the specified program with execvp(). <command-line> is a simple command with arguments separated by single spaces. If the program name contains a /, the part after the last / is taken as ARGV[0]. If the program name is a relative path, the execvp() semantics for finding the program via $PATH apply. After successful program start, socat writes data to stdin of the process and reads from its stdout using a UNIX domain socket generated by socketpair() per default. (example)
- Option groups:
FD,SOCKET,EXEC,FORK,TERMIOS - Useful options:
path,fdin,fdout,chroot,su,su-d,nofork,socktype,pty,stderr,ctty,setsid,pipes,umask,login,sigint,sigquit,netns - See also:
SYSTEM,SHELL
FD:<fdnum>
Uses the file descriptor <fdnum>. It must already exist as a valid UN*X file descriptor โ no imaginary fds bestie ๐
- Option groups:
FD(TERMIOS,REG,SOCKET) - See also:
STDIO,STDIN,STDOUT,STDERR
GOPEN:<filename>
(Generic open) This address type tries to handle any file system entry except directories, usefully. <filename> may be a relative or absolute path. If it already exists, its type is checked:
- In case of a UNIX domain socket, socat connects; if connecting fails, socat assumes a datagram socket and uses
sendto()calls. - If the entry is not a socket, socat opens it applying the
O_APPENDflag. - If it does not exist, it is opened with flag
O_CREATas a regular file. (example) - Option groups:
FD,REG,SOCKET,NAMED,OPEN - See also:
OPEN,CREATE,UNIX-CONNECT
IP-SENDTO:<host>:<protocol>
Opens a raw IP socket. Depending on host specification or option pf, IP protocol version 4 or 6 is used. It uses <protocol> to send packets to <host> [IP address] and receives packets from host, ignoring packets from other hosts. Protocol 255 uses the raw socket with the IP header being part of the data.
- Option groups:
FD,SOCKET,IP4,IP6 - Useful options:
pf,ttl - See also:
IP4-SENDTO,IP6-SENDTO,IP-RECVFROM,IP-RECV,UDP-SENDTO,UNIX-SENDTO
INTERFACE:<interface>
Communicates with a network connected on an interface using raw packets including link level data. <interface> is the name of the network interface. Currently only available on Linux ๐ง
- Option groups:
FD,SOCKET - Useful options:
pf,type - See also:
ip-recv
IP4-SENDTO:<host>:<protocol>
Like IP-SENDTO, but always uses IPv4.
- Option groups:
FD,SOCKET,IP4
IP6-SENDTO:<host>:<protocol>
Like IP-SENDTO, but always uses IPv6.
- Option groups:
FD,SOCKET,IP6
IP-DATAGRAM:<address>:<protocol>
Sends outgoing data to the specified address, which may in particular be a broadcast or multicast address ๐ก Packets arriving on the local socket are checked to see if their source addresses match RANGE or TCPWRAP options. This address type can for example be used for implementing symmetric or asymmetric broadcast or multicast communications.
- Option groups:
FD, SOCKET, IP4, IP6, RANGE - Useful options:
bind,range,tcpwrap,broadcast,ip-multicast-loop,ip-multicast-ttl,ip-multicast-if,ip-add-membership,ip-add-source-membership,ipv6-join-group,ipv6-join-source-group,ttl,tos,pf - See also:
IP4-DATAGRAM,IP6-DATAGRAM,IP-SENDTO,IP-RECVFROM,IP-RECV,UDP-DATAGRAM
IP4-DATAGRAM:<host>:<protocol>
Like IP-DATAGRAM, but always uses IPv4. (example)
- Option groups:
FD,SOCKET,IP4,RANGE
IP6-DATAGRAM:<host>:<protocol>
Like IP-DATAGRAM, but always uses IPv6. Please note that IPv6 does not know broadcasts ๐
- Option groups:
FD,SOCKET,IP6,RANGE
IP-RECVFROM:<protocol>
Opens a raw IP socket of <protocol>. Depending on option pf, IP protocol version 4 or 6 is used. It receives one packet from an unspecified peer and may send one or more answer packets to that peer. This mode is particularly useful with the fork option, where each arriving packet โ from arbitrary peers โ is handled by its own sub process ๐ง This allows a behaviour similar to typical UDP based servers like ntpd or named.
Please note that the reply packets might be fetched as incoming traffic when sender and receiver IP address are identical, because there is no port number to distinguish the sockets. Awkward, but that's the deal.
This address works well with IP-SENDTO address peers (see above). Protocol 255 uses the raw socket with the IP header being part of the data.
See the note about RECVFROM addresses.
- Option groups:
FD,SOCKET,IP4,IP6,CHILD,RANGE - Useful options:
pf,fork,range,ttl,broadcast - See also:
IP4-RECVFROM,IP6-RECVFROM,IP-SENDTO,IP-RECV,UDP-RECVFROM,UNIX-RECVFROM
IP4-RECVFROM:<protocol>
Like IP-RECVFROM, but always uses IPv4.
- Option groups:
FD,SOCKET,IP4,CHILD,RANGE
IP6-RECVFROM:<protocol>
Like IP-RECVFROM, but always uses IPv6.
- Option groups:
FD,SOCKET,IP6,CHILD,RANGE
โจ IP-RECV:<protocol> โจ
Okay bestie, this one opens a raw IP socket of <protocol>. Depending on option pf, IP protocol version 4 or 6 is used. It receives packets from multiple unspecified peers and merges the data. No replies are possible, this is a read-only address, see options -u and -U, and dual addresses. It can be, e.g., addressed by socat IP-SENDTO address peers. Protocol 255 uses the raw socket with the IP header being part of the data. ๐ฐ๏ธ
- Option groups:
FD,SOCKET,IP4,IP6,RANGE - Useful options:
pf,range - See also:
IP4-RECV,IP6-RECV,IP-SENDTO,IP-RECVFROM,UDP-RECV,UNIX-RECV
โจ IP4-RECV:<protocol> โจ
Literally like IP-RECV, but always uses IPv4. No cap. IPv4 forever ๐
- Option groups:
FD,SOCKET,IP4,RANGE
โจ IP6-RECV:<protocol> โจ
Same energy as IP-RECV, but always uses IPv6. Periodt. IPv6 slay ๐
- Option groups:
FD,SOCKET,IP6,RANGE
โจ OPEN:<filename> โจ
Opens <filename> using the open() system call (example). This operation fails on UNIX domain sockets. ๐ญ
Note: This address type is rarely useful in bidirectional mode. Just saying.
- Option groups:
FD,REG,NAMED,OPEN - Useful options:
creat,excl,noatime,nofollow,append,rdonly,wronly,lock,readbytes,ignoreeof - See also:
CREATE,GOPEN,UNIX-CONNECT
โจ OPENSSL:<host>:<port> โจ
Tries to establish a SSL connection to <port> [TCP service] on <host> [IP address] using TCP/IP version 4 or 6 depending on address specification, name resolution, or option pf.
NOTE: Up to version1.7.2.4the server certificate was only checked for validity against the system certificate store orcafileorcapath, but not for match with the serverโs name or its IP address. Since version1.7.3.0socat checks the peer certificate for match with the <host> parameter or the value of theopenssl-commonnameoption. Socat tries to match it against the certificates subjectcommonName, and the certificates extensionsubjectAltNameDNS names. Wildcards in the certificate are supported. ๐
- Option groups:
FD,SOCKET,IP4,IP6,TCP,OPENSSL,RETRY - Useful options:
min-proto-version,cipher,verify,commonname,cafile,capath,certificate,key,compress,bind,pf,connect-timeout,sourceport,retry - See also:
OPENSSL-LISTEN,TCP
โจ OPENSSL-LISTEN:<port> โจ
Listens on tcp <port> [TCP service]. The IP version is 4 or the one specified with pf. When a connection is accepted, this address behaves as SSL server.
Note: You probably want to use the certificate option with this address. ๐
NOTE: The client certificate is only checked for validity againstcafileorcapath, but not for match with the clientโs name or its IP address! ๐
- Option groups:
FD,SOCKET,IP4,IP6,TCP,LISTEN,OPENSSL,CHILD,RANGE,RETRY - Useful options:
pf,min-proto-version,cipher,verify,commonname,cafile,capath,certificate,key,compress,fork,bind,range,tcpwrap,su,reuseaddr,retry - See also:
OPENSSL,TCP-LISTEN
โจ OPENSSL-DTLS-CLIENT:<host>:<port> โจ
Tries to establish a DTLS connection to <port> [UDP service] on <host> [IP address] using UDP/IP version 4 or 6 depending on address specification, name resolution, or option pf.
Socat checks the peer certificates subjectAltName or commonName against the addresses option openssl-commonname or the host name. Wildcards in the certificate are supported. ๐ฆ
Use socat option -b to make datagrams small enough to fit with overhead on the network. Use option -T to prevent indefinite hanging when peer went down quietly. ๐ด
- Option groups:
FD,SOCKET,IP4,IP6,OPENSSL,RETRY - Useful options:
min-proto-version,cipher,verify,commonname,cafile,capath,certificate,key,compress,bind,pf,sourceport,retry,rcvtimeo - See also:
OPENSSL-DTLS-SERVER,OPENSSL-CONNECT,UDP-CONNECT
โจ OPENSSL-DTLS-SERVER:<port> โจ
Listens on UDP <port> [UDP service]. The IP version is 4 or the one specified with pf. When a connection is accepted, this address behaves as DTLS server.
Note: You probably want to use the certificate option with this address. ๐
NOTE: The client certificate is only checked for validity againstcafileorcapath, but not for match with the clientโs name or its IP address! Use socat option-bto make datagrams small enough to fit with overhead on the network. Use option-Tto prevent indefinite hanging when peer went down quietly. ๐
- Option groups:
FD,SOCKET,IP4,IP6,LISTEN,OPENSSL,CHILD,RANGE,RETRY - Useful options:
pf,min-proto-version,cipher,verify,commonname,cafile,capath,certificate,key,compress,fork,bind,range,tcpwrap,su,reuseaddr,retry,rcvtimeo - See also:
OPENSSL-DTLS-CLIENT,OPENSSL-LISTEN,UDP-LISTEN
โจ PIPE:<filename> โจ
If <filename> already exists, it is opened. If it does not exist, a named pipe is created and opened. Beginning with socat version 1.4.3, the named pipe is removed when the address is closed (but see option unlink-close
Note: When a pipe is used for both reading and writing, it works as echo service. ๐
Note: When a pipe is used for both reading and writing, and socat tries to write more bytes than the pipe can buffer (Linux2.4:2048bytes), socat might block. Consider using socat option, e.g.,-b 2048. ๐ญ
- Option groups:
FD,NAMED,OPEN - Useful options:
rdonly,nonblock,group,user,mode,unlink-early - See also: unnamed pipe
โจ PIPE โจ
Creates an unnamed pipe and uses it for reading and writing. It works as an echo, because everything written to it appears immediately as read data. ๐
Note: When socat tries to write more bytes than the pipe can queue (Linux2.4:2048bytes), socat might block. Consider, e.g., using option-b 2048. ๐ต
- Option groups:
FD - See also: named pipe,
SOCKETPAIR
โจ SOCKETPAIR โจ
Creates a socketpair and uses it for reading and writing. It works as an echo, because everything written to it appears immediately as read data. The default socket type is datagram, so it keeps packet boundaries. ๐ฆ
- Option groups:
FD - Useful options:
socktype - See also: unnamed pipe
โจ STALL โจ
The read part of this address never provides any data nor EOF; the write part never gets ready for writing data. This might be useful for testing and for some special scenarios. ๐งช
โจ TEXT:<string> โจ
The text provided as parameter is taken as input data: it is buffered in an internal pipe and then processed as usual. The standard conversions are performed on the string, so you may check how parameters are parsed and prepared which is critical for addresses like EXEC.
Output on this address is sent to stdout. Thus this address can replace constructs like:
echo "<string>" | socat STDIO TCP:<server>:<port>
with:
socat TEXT:"<string>\n" TCP:<server>:<port>
Have a look at the example with sudo below. ๐
โจ POSIXMQ-READ:/<mqueue> โจ
Opens or creates the specified POSIX message queue and reads messages (packets). It keeps the packet boundaries. ๐ฌ
This is a read-only address, see options -u and -U and dual addresses.
Socat provides this address type only on Linux because POSIX MQ is based on UNIX filedescriptors there. ๐ง
- Useful options:
posixmq-priority,unlink-early,unlink-close,o-nonblock,o-creat,o-excl,umask
โจ POSIXMQ-RECEIVE:/<mqueue> โจ
โจ POSIXMQ-RECV:/<mqueue> โจ
Opens or creates the specified POSIX message queue and reads one message (packet). ๐จ
This is a read-only address. See POSIXMQ-READ for more info.
Example: POSIX MQ recv with fork. ๐ด
- Useful options:
posixmq-priority,fork,max-children,unlink-early,unlink-close,o-creat,o-excl,umask
โจ POSIXMQ-SEND:/<mqueue> โจ
Opens or creates the specified POSIX message queue and writes messages (packets). โ๏ธ
This is a write-only address. See POSIXMQ-READ for more info.
(Example)
- Useful options:
posixmq-priority,posixmq-flush,fork,max-children,unlink-early,unlink-close,o-creat,o-excl,umask
โจ POSIXMQ-WRITE:/<mqueue> โจ
Does the same as POSIXMQ-SEND. Literally identical. ๐
โจ POSIXMQ-BIDIRECTIONAL:/mqueue โจ
โจ POSIXMQ:/mqueue โจ
Opens or creates the specified POSIX message queue in read and/or write mode depending on context, then reads and/or writes messages (packets). In bidirectional mode this is just another echo service. POSIXMQ refuses bidirectional mode to prevent unwanted flushing of queue; use POSIXMQ-BIDIRECTIONAL when needed.
See POSIXMQ-READ and POSIXMQ-SEND for more info. ๐
โจ PROXY:<proxy>:<hostname>:<port> โจ
Connects to an HTTP proxy server on port 8080 using TCP/IP version 4 or 6 depending on address specification, name resolution, or option pf, and sends a CONNECT request for hostname:port. If the proxy grants access and succeeds to connect to the target, data transfer between socat and the target can start (example). Note that the traffic need not be HTTP but can be an arbitrary protocol. ๐
- Option groups:
FD,SOCKET,IP4,IP6,TCP,HTTP,RETRY - Useful options:
proxyport,ignorecr,proxyauth,resolve,crnl,bind,connect-timeout,mss,sourceport,retry - See also:
SOCKS,TCP
โจ PTY โจ
Generates a pseudo terminal (pty) and uses its master side. Another process may open the ptyโs slave side using it like a serial line or terminal. (example). If both the ptmx and the openpty mechanisms are available, ptmx is used (POSIX). ๐ฅ๏ธ
- Option groups:
FD,NAMED,PTY,TERMIOS - Useful options:
link,openpty,wait-slave,mode,user,group - See also:
UNIX-LISTEN,PIPE,EXEC,SYSTEM,SHELL
โจ READLINE โจ
Uses GNU readline and history on stdio to allow editing and reusing input lines (example). This requires the GNU readline and history libraries. Note that stdio should be a (pseudo) terminal device, otherwise readline does not seem to work. ๐
- Option groups:
FD,READLINE,TERMIOS - Useful options:
history,noecho - See also:
STDIO
๐ธ SCTP-CONNECT ๐ธ
SCTP-CONNECT:<host>:<port>
Opens up an SCTP stream connection to the <host> you named [IP address] on <port> [TCP service]. Which IP version it uses โ 4 or 6 โ depends on how you wrote the address, on name resolution, or on the pf option. Slay.
- Option groups:
FD,SOCKET,IP4,IP6,SCTP,CHILD,RETRY - Useful options:
bind,pf,connect-timeout,tos,mtudiscover,mtudiscover6,sctp-maxseg,sctp-nodelay,nonblock,sourceport,retry,readbytes - See also:
SCTP4-CONNECT,SCTP6-CONNECT,SCTP-LISTEN,TCP-CONNECT
๐ฆ SCTP4-CONNECT ๐ฆ
SCTP4-CONNECT:<host>:<port>
Same energy as SCTP-CONNECT, except it's IPv4 only, periodt.
- Option groups:
FD,SOCKET,IP4,SCTP,CHILD,RETRY
๐ SCTP6-CONNECT ๐
SCTP6-CONNECT:<host>:<port>
Also like SCTP-CONNECT, but this one is IPv6 only. No crossover, no drama.
- Option groups:
FD,SOCKET,IP6,SCTP,CHILD,RETRY
โจ SCTP-LISTEN โจ
SCTP-LISTEN:<port>
Sits there listening on <port> [TCP service] and accepts one SCTP connection. The IP version is 4, or whatever you picked with the address option pf, the socat option (-4, -6), or the environment variable SOCAT_DEFAULT_LISTEN_IP.
Heads up bestie: opening this address usually blocks until a client actually connects. So likeโฆ don't be surprised when it just sits there. It's waiting. That's the whole job. ๐ซถ
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP4,IP6,SCTP,RETRY - Useful options:
crnl,fork,bind,range,tcpwrap,pf,max-children,backlog,accept-timeout,sctp-maxseg,sctp-nodelay,su,reuseaddr,retry - See also:
SCTP4-LISTEN,SCTP6-LISTEN,TCP-LISTEN,SCTP-CONNECT
๐ SCTP4-LISTEN ๐
SCTP4-LISTEN:<port>
Like SCTP-LISTEN, but IPv4 only, full stop.
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP4,SCTP,RETRY
๐ SCTP6-LISTEN ๐
SCTP6-LISTEN:<port>
Like SCTP-LISTEN, but IPv6 only. Living its best v6 life.
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP6,SCTP,RETRY
๐ฅ SOCKET-CONNECT ๐ฅ
SOCKET-CONNECT:<domain>:<protocol>:<remote-address>
Bestie this one is the raw, DIY, build-it-yourself address. It creates a stream socket using the first and second socket parameters you hand it, plus SOCK_STREAM (peep man socket(2)), and connects to the remote-address.
Both socket parameters have to be given as int numbers. So go consult your OS documentation and your include files to find the right values โ no guessing, fr fr. And the remote-address must be the data representation of a sockaddr structure, without the sa_family and (BSD) sa_len components.
Also, lowkey iconic detail: beyond the options of the groups listed below, you can also use options of higher level protocols if you apply the socat option -g.
- Option groups:
FD,SOCKET,CHILD,RETRY - Useful options:
bind,setsockopt, - See also:
TCP,UDP-CONNECT,UNIX-CONNECT,SOCKET-LISTEN,SOCKET-SENDTO
๐ซ SOCKET-DATAGRAM ๐ซ
SOCKET-DATAGRAM:<domain>:<type>:<protocol>:<remote-address>
Creates a datagram socket using the first three socket parameters you give it (see man socket(2)) and sends outgoing data off to the remote-address. All three socket parameters must be specified as int numbers โ again, consult your OS docs and include files for the correct values. The remote-address has to be the data representation of a sockaddr structure, without sa_family and (BSD) sa_len components.
And same as before: you can also reach for options of higher level protocols when you apply the socat option -g. ๐
- Option groups:
FD,SOCKET,RANGE - Useful options:
bind,range,setsockopt, - See also:
UDP-DATAGRAM,IP-DATAGRAM,SOCKET-SENDTO,SOCKET-RECV,SOCKET-RECVFROM
๐ SOCKET-LISTEN ๐
SOCKET-LISTEN:<domain>:<protocol>:<local-address>
Creates a stream socket from the first and second socket parameters plus SOCK_STREAM (see man socket(2)) and then justโฆ waits for incoming connections on local-address. The two socket parameters have to be int numbers โ check your OS documentation and include files, you got this. The local-address must be the data representation of a sockaddr structure without sa_family and (BSD) sa_len components.
And yes, the -g socat option thing again: you can use options of higher level protocols on top of the listed groups.
- Option groups:
FD,SOCKET,LISTEN,RANGE,CHILD,RETRY - Useful options:
setsockopt,setsockopt-listen, - See also:
TCP,UDP-CONNECT,UNIX-CONNECT,SOCKET-LISTEN,SOCKET-SENDTO,SOCKET-SENDTO
๐ SOCKET-RECV ๐
SOCKET-RECV:<domain>:<type>:<protocol>:<local-address>
Makes a socket out of the three socket parameters you give it (see man socket(2)) and binds it to <local-address>. Then it receives whatever data arrives. The three parameters have to be int numbers โ OS documentation and include files, you know the drill. The local-address must be the data representation of a sockaddr structure without sa_family and (BSD) sa_len components.
- Option groups:
FD,SOCKET,RANGE - Useful options:
range,setsockopt,setsockopt-listen - See also:
UDP-RECV,IP-RECV,UNIX-RECV,SOCKET-DATAGRAM,SOCKET-SENDTO,SOCKET-RECVFROM
๐ง SOCKET-RECVFROM ๐ง
SOCKET-RECVFROM:<domain>:<type>:<protocol>:<local-address>
Same setup: creates a socket from the three socket parameters (see man socket(2)) and binds it to <local-address>. It receives arriving data and sends replies back to whoever sent it. The first three parameters have to be specified as int numbers โ go look them up in your OS documentation and include files. The local-address must be the data representation of a sockaddr structure without sa_family and (BSD) sa_len components.
Also peep the note about RECVFROM addresses. ๐
- Option groups:
FD,SOCKET,CHILD,RANGE - Useful options:
fork,range,setsockopt,setsockopt-listen - See also:
UDP-RECVFROM,IP-RECVFROM,UNIX-RECVFROM,SOCKET-DATAGRAM,SOCKET-SENDTO,SOCKET-RECV
๐ SOCKET-SENDTO ๐
SOCKET-SENDTO:<domain>:<type>:<protocol>:<remote-address>
Creates a socket using the three socket parameters you supply (see man socket(2)). It sends outgoing data to the given address and receives replies. The three parameters have to be specified as int numbers โ consult your OS documentation and include files for the right values. The remote-address must be the data representation of a sockaddr structure without sa_family and (BSD) sa_len components.
- Option groups:
FD,SOCKET - Useful options:
bind,setsockopt,setsockopt-listen - See also:
UDP-SENDTO,IP-SENDTO,UNIX-SENDTO,SOCKET-DATAGRAM,SOCKET-RECVSOCKET-RECVFROM
๐ ACCEPT-FD ๐
ACCEPT-FD:<fdnum>
This one expects a listening socket sitting in <fdnum> and accepts one connection โ or more than one, if you pass the option fork. It's the move when you're running under systemd control with "inetd mode".
Example: (example)
- Option groups:
FD, SOCKET, TCP, CHILD, RETRY - Useful options:
fork,range,sourceport,lowport,tcpwrap
๐ถ๏ธ SOCKS4 ๐ถ๏ธ
SOCKS4:<socks-server>:<host>:<port>
Connects through <socks-server> [IP address] to <host> [IPv4 address] on <port> [TCP service], using the socks version 4 protocol over IP version 4 or 6 โ which one depends on your address specification, name resolution, or the pf option (example).
- Option groups:
FD,SOCKET,IP4,IP6,TCP,SOCKS4,RETRY - Useful options:
socksuser,socksport,sourceport,pf,retry - See also:
SOCKS5,SOCKS4A,PROXY,TCP
๐ธ SOCKS4A ๐ธ
SOCKS4A:<socks-server>:<host>:<port>
Like SOCKS4, but it speaks socks protocol version 4a, which means it leaves host name resolution up to the socks server. Delegation, queen behavior.
- Option groups:
FD,SOCKET,IP4,IP6,TCP,SOCKS4,RETRY
๐ SOCKS5-CONNECT ๐
SOCKS5-CONNECT:<socks-server>:<socks-port>:<target-host>:<target-port>
SOCKS5-CONNECT:<socks-server>:<target-host>:<target-port>
Connects through <socks-server> [IP address] to <target-host> [IPv4 address] on <target-port> [TCP service], using the socks version 5 protocol over TCP. Just so you know: currently no authentication mechanism is provided.
- Option groups:
FD, SOCKET, IP4, IP6, TCP, CHILD, RETRY - Useful options:
socksport,socksuser,sockspass,sourceport,pf,retry - See also:
SOCKS5-LISTEN,SOCKS4,SOCKS4A,PROXY,TCP
๐ SOCKS5-LISTEN ๐
SOCKS5-LISTEN:<socks-server>:<socks-port>:<listen-host>:<listen-port>
SOCKS5-LISTEN:<socks-server>:<listen-host>:<listen-port>
Connects to <socks-server> [IP address] using socks version 5 protocol over TCP, and makes it listen for incoming connections on <listen-port> [TCP service], binding to <-listen-host> [IPv4 address]. And again, currently no authentication mechanism is provided.
- Option groups:
FD, SOCKET, IP4, IP6, TCP, CHILD, RETRY - Useful options:
sourceport,pf,retry - See also:
SOCKS5-CONNECT,
๐ STDERR ๐
STDERR
Uses file descriptor 2.
This is a write-only address โ check the options -u and -U, and the dual addresses situation.
- Option groups:
FD (TERMIOS,REG,SOCKET) - See also:
FD
๐ STDIN ๐
STDIN
Uses file descriptor 0.
This is a read-onlyโฆ okay, read-only address โ see the options -u and -U, and dual addresses.
- Option groups:
FD (TERMIOS,REG,SOCKET) - Useful options:
readbytes - See also:
FD
๐ซถ STDIO ๐ซถ
STDIO
Uses file descriptor 0 for reading, and 1 for writing. Both worlds, one address. Main character energy.
- Option groups:
FD (TERMIOS,REG,SOCKET) - Useful options:
readbytes - See also:
FD
โญ STDOUT โญ
STDOUT
Uses file descriptor 1.
This is a write-only address โ see options -u and -U, plus dual addresses.
- Option groups:
FD (TERMIOS,REG,SOCKET) - See also:
FD
๐ SHELL ๐
SHELL:<shell-command>
SHELL
Forks a sub process that sets up communication with its parent process and invokes the program you specified, using the configured shell ($SHELL). Quick notes bestie: <shell-command> [string] must not contain , or !!, and : plus shell meta characters may have to be protected. After the program starts successfully, socat writes data to the process's stdin and reads from its stdout.
And when you invoke it with no parameter at all? It opens an interactive shell. Go off. ๐
- Option groups:
FD,SOCKET,EXEC,FORK,TERMIOS - Useful options:
path,fdin,fdout,chroot,su,su-d,nofork,socktype,pty,stderr,ctty,setsid,pipes,umask,sigint,sigquit - See also:
EXEC,SYSTEM
SYSTEM:<shell-command>
Okay bestie, this one forks a sub process ๐ด โ that little sub process sets up communication with its parent process and then invokes the program you specified using system(). Two things you literally cannot do: <shell-command> [string] must not contain , or "!!", and shell meta characters may have to be protected. After a successful program start, socat writes data to the stdin of the process and reads from its stdout. Iconic.
- Option groups:
FD,SOCKET,EXEC,FORK,TERMIOS - Useful options:
path, fdin, fdout, chroot, su, su-d, nofork, socktype, pty, stderr, ctty, setsid, pipes, umask, sigint, sigquit, netns - See also:
EXEC,SHELL
TCP:<host>:<port>
Connects to <port> [TCP service] on <host> [IP address] using TCP/IP version 4 or 6, depending on address specification, name resolution, or option pf. The way this justโฆ works ๐
- Option groups:
FD,SOCKET,IP4,IP6,TCP,RETRY - Useful options:
connect-timeout, retry, sourceport, netns, crnl, bind, pf, tos, mtudiscover, mtudiscover6, mss, nodelay, nonblock, readbytes - See also:
TCP4,TCP6,TCP-LISTEN,UDP,SCTP-CONNECT,UNIX-CONNECT
TCP4:<host>:<port>
Same as TCP, but it only supports the IPv4 protocol (example). No IPv6 energy here, just vibes.
- Option groups:
FD,SOCKET,IP4,TCP,RETRY
TCP6:<host>:<port>
Same as TCP, but it only supports the IPv6 protocol. Six-y and thriving ๐
- Option groups:
FD,SOCKET,IP6,TCP,RETRY
TCP-LISTEN:<port>
Listens on <port> [TCP service] and accepts a TCP/IP connection. The IP version is 4, or whatever you specified with address option pf, socat option (-4, -6), or the environment variable SOCAT_DEFAULT_LISTEN_IP. Heads up fr fr: opening this address usually blocks until a client connects. It's giving "waiting by the phone" ๐ญ
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP4,IP6,TCP,RETRY - Useful options:
crnl, fork, bind, range, tcpwrap, pf, max-children, backlog, accept-timeout, mss, su, reuseaddr, retry, cool-write - See also:
TCP4-LISTEN,TCP6-LISTEN,UDP-LISTEN,SCTP-LISTEN,UNIX-LISTEN,OPENSSL-LISTEN,TCP-CONNECT
TCP4-LISTEN:<port>
Same as TCP-LISTEN, but it only supports the IPv4 protocol (example).
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP4,TCP,RETRY
TCP6-LISTEN:<port>
Same as TCP-LISTEN, but it only supports the IPv6 protocol.
- Additional useful option:
ipv6only - Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP6,TCP,RETRY
TUN[:<if-addr>/<bits>]
Creates a Linux TUN/TAP device and optionally assigns it the address and netmask given by the parameters. The resulting network interface is almost ready for use by other processes โ socat serves its "wire side" ๐ง
This address requires read and write access to the tunnel cloning device, usually /dev/net/tun, plus permission to set some ioctl()s. And listen: option iff-up is required to immediately activate the interface! ๐
Note: If you intend to transfer packets between two Socat "wire sides" you need a protocol that keeps packet boundaries, e.g.UDP; TCP might work with option nodelay.
- Option groups:
FD,NAMED,OPEN,TUN - Useful options:
iff-up, tun-device, tun-name, tun-type, interface-mtu, iff-no-pi, netns - See also:
ip-recv
UDP:<host>:<port>
Connects to <port> [UDP service] on <host> [IP address] using UDP/IP version 4 or 6, depending on address specification, name resolution, or option pf.
Now the important part, bestie โ because of UDP protocol properties, no real connection is established. Data has to be sent for connecting to the server, and no end-of-file condition can be transported. Since version 1.8.1.0, the socket sends, when shutting down, a zero length UDP packet that might trigger EOF on the peer (implicit option shut-null). Restore the old behaviour with option shut-none.
- Option groups:
FD,SOCKET,IP4,IP6 - Useful options:
ttl, tos, bind, sourceport, pf - See also:
UDP4,UDP6,UDP-LISTEN,TCP,IP
UDP4:<host>:<port>
Same as UDP, but it only supports the IPv4 protocol.
- Option groups:
FD,SOCKET,IP4
UDP6:<host>:<port>
Same as UDP, but it only supports the IPv6 protocol.
- Option groups:
FD,SOCKET,IP6
UDP-DATAGRAM:<address>:<port>
Sends outgoing data to the specified address, which may in particular be a broadcast or multicast address ๐ก Packets arriving on the local socket are checked for the correct remote port only when option sourceport is used (this is a change with Socat version 1.7.4.0), and only if their source addresses match RANGE or TCPWRAP options. This address type can for example be used for implementing symmetric or asymmetric broadcast or multicast communications.
- Option groups:
FD,SOCKET,IP4,IP6,RANGE - Useful options:
bind, range, tcpwrap, broadcast, ip-multicast-loop, ip-multicast-ttl, ip-multicast-if, ip-add-membership, ip-add-source-membership, ipv6-join-group, ipv6-join-source-group, ttl, tos, sourceport, pf - See also:
UDP4-DATAGRAM,UDP6-DATAGRAM,UDP-SENDTO,UDP-RECVFROM,UDP-RECV,UDP-CONNECT,UDP-LISTEN,IP-DATAGRAM
UDP4-DATAGRAM:<address>:<port>
Same as UDP-DATAGRAM, but it only supports the IPv4 protocol (example1, example2).
- Option groups:
FD,SOCKET,IP4, RANGE
UDP6-DATAGRAM:<address>:<port>
Same as UDP-DATAGRAM, but it only supports the IPv6 protocol.
- Option groups:
FD,SOCKET,IP6,RANGE
UDP-LISTEN:<port>
Waits for a UDP/IP packet arriving on <port> [UDP service] and connects back to the sender. The accepted IP version is 4, or the one specified with option pf.
Please note that, because of UDP protocol properties, no real connection is established ๐ญ โ data has to arrive from the peer first, so opening this address usually blocks until a client connects. Furthermore, no end-of-file condition is specified in UDP. Since version 1.8.1.0, the socket sends, when shutting down, a zero length UDP packet that might trigger EOF on the peer (implicit option shut-null). Restore the old behaviour with option shut-none.
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP4,IP6 - Useful options:
fork, bind, range, pf - See also:
UDP,UDP4-LISTEN,UDP6-LISTEN,TCP-LISTEN
UDP4-LISTEN:<port>
Same as UDP-LISTEN, but it only supports the IPv4 protocol.
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP4
UDP6-LISTEN:<port>
Same as UDP-LISTEN, but it only supports the IPv6 protocol.
- Option groups:
FD,SOCKET,LISTEN,CHILD,RANGE,IP6
UDP-SENDTO:<host>:<port>
Communicates with the specified peer socket, defined by <port> [UDP service] on <host> [IP address], using UDP/IP version 4 or 6 depending on address specification, name resolution, or option pf. It sends packets to and receives packets from that peer socket only ๐ซถ This address effectively implements a datagram client. It works well with socat UDP-RECVFROM and UDP-RECV address peers. When the peer might send data first, UDP-DATAGRAM is preferable.
- Option groups:
FD,SOCKET,IP4,IP6 - Useful options:
ttl, tos, bind, sourceport, pf - See also:
UDP4-SENDTO,UDP6-SENDTO,UDP-RECVFROM,UDP-RECV,UDP-CONNECT,UDP-LISTEN,IP-SENDTO
UDP4-SENDTO:<host>:<port>
Same as UDP-SENDTO, but it only supports the IPv4 protocol.
- Option groups:
FD,SOCKET,IP4
UDP6-SENDTO:<host>:<port>
Same as UDP-SENDTO, but it only supports the IPv6 protocol.
- Option groups:
FD,SOCKET,IP6
UDP-RECVFROM:<port>
Creates a UDP socket on <port> [UDP service] using UDP/IP version 4 or 6 depending on option pf. It receives one packet from an unspecified peer and may send one or more answer packets to that peer. This mode is particularly useful with the fork option, where each arriving packet โ from arbitrary peers โ is handled by its own sub process ๐ฅ This allows a behaviour similar to typical UDP based servers like ntpd or named. This address works well with socat UDP-SENDTO address peers.
Note: When the second address fails before entering the transfer loop the packet is dropped. Use optionretryorforeveron the second address to avoid data loss. When you know the peer address,UDP-DATAGRAMis preferable.
- Option groups:
FD,SOCKET,IP4,IP6,CHILD,RANGE - Useful options:
fork, ttl, tos, bind, sourceport, pf - See also:
UDP4-RECVFROM,UDP6-RECVFROM,UDP-SENDTO,UDP-RECV,UDP-CONNECT,UDP-LISTEN,IP-RECVFROM,UNIX-RECVFROM
UDP4-RECVFROM:<port>
Same as UDP-RECVFROM, but it only supports the IPv4 protocol.
- Option groups:
FD,SOCKET,IP4,CHILD,RANGE
UDP6-RECVFROM:<port>
Same as UDP-RECVFROM, but it only supports the IPv6 protocol.
- Option groups:
FD,SOCKET,IP6,CHILD,RANGE
UDP-RECV:<port>
Creates a UDP socket on <port> [UDP service] using UDP/IP version 4 or 6 depending on option pf. It receives packets from multiple unspecified peers and merges the data. No replies are possible ๐ It works well with, e.g., socat UDP-SENDTO address peers; it behaves similar to a syslog server.
This is a read-only address โ see options -u and -U, and dual addresses.
Note: if you need theforkoption, useUDP-RECVFROMin unidirectional mode (with option-u) instead.
- Option groups:
FD,SOCKET,IP4,IP6,RANGE - Useful options:
pf, bind, sourceport, ttl, tos - See also:
UDP4-RECV,UDP6-RECV,UDP-SENDTO,UDP-RECVFROM,UDP-CONNECT,UDP-LISTEN,IP-RECV,UNIX-RECV
UDP4-RECV:<port>
Same as UDP-RECV, but it only supports the IPv4 protocol.
- Option groups:
FD,SOCKET,IP4,RANGE
UDP6-RECV:<port>
Same as UDP-RECV, but it only supports the IPv6 protocol.
- Option groups:
FD,SOCKET,IP6,RANGE
UDPLITE-CONNECT:<host>:<port>
UDPLITE4-CONNECT:<host>:<port>
UDPLITE6-CONNECT:<host>:<port>
UDPLITE-DATAGRAM:<address>:<port>
UDPLITE4-DATAGRAM:<address>:<port>
UDPLITE6-DATAGRAM:<address>:<port>
UDPLITE-LISTEN:<port>
UDPLITE4-LISTEN:<port>
UDPLITE6-LISTEN:<port>
UDPLITE-SENDTO:<host>:<port>
UDPLITE4-SENDTO:<host>:<port>
UDPLITE6-SENDTO:<host>:<port>
UDPLITE-RECVFROM:<port>
UDPLITE4-RECVFROM:<port>
UDPLITE6-RECVFROM:<port>
UDPLITE-RECV:<port>
UDPLITE4-RECV:<port>
UDPLITE6-RECV:<port>
The UDPLITE addresses are almost identical to the related UDP addresses ๐ โ they just use the UDP-Lite protocol and have the additional UDPLITE option group. The whole squad, slaying in a row.
UNIX-CONNECT:<filename>โ connects to <filename> on the assumption that it is, in fact, a UNIX domain socket. And bestie, if <filename> doesn't exist? error. If it exists but isn't a UNIX domain socket? also error. And if it is a UNIX domain socket but literally nobody is listening? you guessed it, error. three strikes, no notes. ๐- Option groups: FD,SOCKET,NAMED,RETRY,UNIX
- Useful options: bind
- See also: UNIX-LISTEN, UNIX-SENDTO, TCP
UNIX-LISTEN:<filename>โ listens on <filename> using a UNIX domain stream socket and accepts a connection. If <filename> exists and isn't a socket, that's an error, periodt. And if <filename> exists and is a UNIX domain socket, then binding to the address fails โ so use optionunlink-early! ๐ซถ Also heads up: opening this address usually blocks until a client connects (main character waiting for her moment fr). Starting with socat version1.4.3, the file system entry gets removed when this address is closed (but see optionunlink-close) (example). โจ- Option groups: FD,SOCKET,NAMED,LISTEN,CHILD,RETRY,UNIX
- Useful options: fork, umask, mode, user, group, unlink-early
- See also: UNIX-CONNECT, UNIX-RECVFROM, UNIX-RECV, TCP-LISTEN
UNIX-SENDTO:<filename>โ talks to the specified peer socket, defined by[<filename>], assuming it's a UNIX domain datagram socket. It sends packets to that peer socket and receives packets from that peer socket only, no side quests. ๐ Quick note: you might need to bind the local socket to an address (like/tmp/sock1, which must not exist beforehand). This address type is lowkey made for socatUNIX-RECVFROMandUNIX-RECVaddress peers, they're a duo. ๐- Option groups: FD,SOCKET,NAMED,UNIX
- Useful options: bind
- See also: UNIX-RECVFROM, UNIX-RECV, UNIX-CONNECT, UDP-SENDTO, IP-SENDTO
UNIX-RECVFROM:<filename>โ creates a UNIX domain datagram socket[<filename>]. It receives one packet and may send one or more answer packets back to that peer. This mode is especially iconic with theforkoption, where each arriving packet โ from whatever arbitrary peers โ gets handled by its own little sub process. So organized. ๐ This address works well with socatUNIX-SENDTOaddress peers.- Option groups: FD,SOCKET,NAMED,CHILD,UNIX
- See the note about RECVFROM addresses.
- Useful options: fork, umask
- See also: UNIX-SENDTO, UNIX-RECV, UNIX-LISTEN, UDP-RECVFROM, IP-RECVFROM
UNIX-RECV:<filename>โ creates a UNIX domain datagram socket[<filename>]. It receives packets from multiple unspecified peers and merges all the data together (chaos but make it tidy). No replies are possible โ this is a read-only address, so peep options-uand-U, and dual addresses. It can be addressed by, like, socatUNIX-SENDTOaddress peers. Behaves similar to a syslog server, no cap. ๐- Option groups: FD,SOCKET,NAMED,UNIX
- Useful options: umask
- See also: UNIX-SENDTO, UNIX-RECVFROM, UNIX-LISTEN, UDP-RECV, IP-RECV
UNIX-CLIENT:<filename>โ communicates with the specified peer socket, defined by[<filename>], assuming it's a UNIX domain socket. It first tries to connect and, if that fails, assumes it's a datagram socket โ so it supports both types. Versatile queen, she contains multitudes. ๐- Option groups: FD,SOCKET,NAMED,UNIX
- Useful options: bind
- See also: UNIX-CONNECT, UNIX-SENDTO, GOPEN
VSOCK-CONNECT:<cid>:<port>โ establishes a VSOCK stream connection to the specified <cid>[VSOCK cid]and <port>[VSOCK port]. โจ- Option groups: FD,SOCKET,CHILD,RETRY
- Useful options: bind, connect-timeout, retry, readbytes
- See also: VSOCK-LISTEN,
VSOCK-LISTEN:<port>โ listens on <port>[VSOCK port]and accepts a VSOCK connection. Heads up though: opening this address usually blocks until a client connects. ๐ฆ- Option groups: FD,SOCKET,LISTEN,CHILD,RETRY
- Useful options: fork, bind, max-children, backlog, su, reuseaddr, retry
- See also: VSOCK-CONNECT
ABSTRACT-CONNECT:<string>ABSTRACT-LISTEN:<string>ABSTRACT-SENDTO:<string>ABSTRACT-RECVFROM:<string>ABSTRACT-RECV:<string>ABSTRACT-CLIENT:<string>
The ABSTRACT addresses are almost identical to the related UNIX addresses, except โ plot twist โ they don't address file system based sockets, they address an alternate UNIX domain address space. To pull this off, the socket address strings get prefixed with "\0" internally. This feature is available (only?) on Linux. ๐ง Option groups are the same as with the related UNIX addresses, except that the ABSTRACT addresses are not a member of the NAMED group.
- Useful options: netns
โจ ADDRESS OPTIONS โจ
Okay so address options are the little extra settings you can apply to address specifications to influence how the addresses get opened and what the resulting data channels are like. It's giving โจcustomizationโจ.
For technical reasons, not every option can be applied to every address type โ like, applying a socket option to a regular file? that's just gonna fail, bestie. To catch most of these useless combos as early as the open phase, socat introduced the concept of option groups. Each option belongs to one or more option groups. You can only use an option with address types that support at least one of its option groups (but see option -g).
Address options have data types that their values have to conform to. Every address option is either just a keyword, or a keyword followed by =value, where value has to match the option's type. Some address options manipulate parameters of system calls โ e.g., option sync sets the O_SYNC flag with the open() call. Other options cause a system or library call โ e.g., with option ttl=value the setsockopt(fd, SOL_IP, IP_TTL, value, sizeof(int)) call is applied. Other options set internal socat variables used during data transfer โ e.g., crnl causes explicit character conversions. And a few options have way more complex implementations โ e.g., su-d (substuser-delayed) inquires some user and group infos, stores them, and applies them later after a possible chroot() call. ๐ค
If you give multiple options to an address, their sequence in the address specification has (almost) no effect on the sequence of their execution/application. Instead, socat has an option phase model built in that tries to bring the options into a useful order. Some options even exist in different forms (e.g., unlink, unlink-early, unlink-late) specifically to control when they execute. Timing is everything, iykyk. โฐ
If you specify the same option more than once within one address specification โ with equal or different values โ the effect depends on the kind of option. Options that result in function calls like setsockopt() cause multiple invocations. With options that set parameters for a required call like open(), or that set internal flags, the value of the last option occurrence is the one that's effective.
The existence or semantics of many options are system dependent. Socat usually does NOT try to emulate missing libc or kernel features โ it just provides an interface to the underlying system. So if an operating system lacks a feature, the related option is simply not available on that platform. no notes, it's just how she is. ๐ซถ
The following paragraphs introduce just the more common address options. For a more comprehensive reference, and to find info about canonical option names, alias names, option phases, and platforms, see file xio.help.
๐ FD option group ๐
This option group contains options that get applied to a UN*X style file descriptor, no matter how it was generated. And because all current socat address types are file descriptor based, these options may be applied to any address. slay.
Note: Some of these options are also members of another option group, which provides another, non-fd based mechanism. For these options, it depends on the actual address type and its option groups which mechanism gets used. The second, non-fd based mechanism is prioritized. ๐
cloexec[=<bool>]โ sets theFD_CLOEXECflag with thefcntl()system call to value <bool>. If set, the file descriptor is closed onexec()family function calls. Socat internally handles this flag for the fds it controls, so in most cases you won't even need to apply this option. ๐setlk[=<bool>]โ tries to set a discretionary write lock on the whole file using thefcntl(fd, F_SETLK, ...)system call. If the file is already locked, this call results in an error. On Linux, when the file permissions for group are"S"(g-x,g+s), and the file system is locally mounted with the"mand"option, the lock is mandatory โ meaning it prevents other processes from opening the file. ๐ณsetlkw[=<bool>]โ tries to set a discretionary waiting write lock on the whole file using thefcntl(fd, F_SETLKW, ...)system call. If the file is already locked, this call blocks. See optionsetlkfor info about making this lock mandatory.setlk-rd[=<bool>]โ tries to set a discretionary read lock on the whole file using thefcntl(fd, F_SETLK, ...)system call. If the file is already write locked, this call results in an error. See optionsetlkfor info about making this lock mandatory.setlkw-rd[=<bool>]โ tries to set a discretionary waiting read lock on the whole file using thefcntl(fd, F_SETLKW, ...)system call. If the file is already write locked, this call blocks. See optionsetlkfor info about making this lock mandatory.flock-ex[=<bool>]โ tries to set a blocking exclusive advisory lock on the file using theflock(fd, LOCK_EX)system call. Socat hangs in this call if the file is locked by another process. ๐ญflock-ex-nb[=<bool>]โ tries to set a nonblocking exclusive advisory lock on the file using theflock(fd, LOCK_EX|LOCK_NB)system call. If the file is already locked, this option results in an error.flock-sh[=<bool>]โ tries to set a blocking shared advisory lock on the file using theflock(fd, LOCK_SH)system call. Socat hangs in this call if the file is locked by another process.flock-sh-nb[=<bool>]โ tries to set a nonblocking shared advisory lock on the file using theflock(fd, LOCK_SH|LOCK_NB)system call. If the file is already locked, this option results in an error.lock[=<bool>]โ sets a blocking lock on the file. Uses thesetlkorflockmechanism depending on availability on the particular platform. If both are available, the POSIX variant (setlkw) is used. ๐
okay bestie, these next address options are giving ownership, permissions, and file flags energy. let's get into it. ๐
user=<user>โ sets the<user>(owner) of the stream. If the address is member of theNAMEDoption group, socat uses thechown()system call after opening the file or binding to the UNIX domain socket (race condition!). Without filesystem entry, socat sets the user of the stream using thefchown()system call. These calls might require root privilege. ๐user-late=<user>โ sets the owner of the fd to<user>with thefchown()system call after opening or connecting the channel. This is useful only on file system entries. โจgroup=<group>โ sets the<group>of the stream. If the address is member of theNAMEDoption group, socat uses thechown()system call after opening the file or binding to the UNIX domain socket (race condition!). Without filesystem entry, socat sets the group of the stream with thefchown()system call. These calls might require group membership or root privilege. ๐group-late=<group>โ sets the group of the fd to<group>with thefchown()system call after opening or connecting the channel. This is useful only on file system entries. โจmode=<mode>โ sets the<mode>[mode_t](permissions) of the stream. If the address is member of theNAMEDoption group and uses theopen()orcreat()call, the mode is applied with these. If the address is member of theNAMEDoption group without using these system calls, socat uses thechmod()system call after opening the filesystem entry or binding to the UNIX domain socket (race condition!). Otherwise, socat sets the mode of the stream usingfchmod()which, btw, might not have any effect. These calls might require ownership or root privilege. Note: this option can only tighten the permissions implied by processes umask. See optionumaskto loosen permissions.perm-late=<mode>โ sets the permissions of the fd to value<mode>[mode_t]using thefchmod()system call after opening or connecting the channel. This is useful only on file system entries. โจappend[=<bool>]โ always writes data to the actual end of file. If the address is member of theOPENoption group, socat uses theO_APPENDflag with theopen()system call (example). Otherwise, socat applies thefcntl(fd, F_SETFL, O_APPEND)call. ๐nonblock[=<bool>]โ tries to open or use file in nonblocking mode. Its only effects are that theconnect()call of TCP addresses does not block, and that opening a named pipe for reading does not block. If the address is member of theOPENoption group, socat uses theO_NONBLOCKflag with theopen()system call. Otherwise, socat applies thefcntl(fd, F_SETFL, O_NONBLOCK)call. ๐ฆbinary[=<bool>]โ opens the file in binary mode to avoid implicit line terminator conversions (Cygwin). ๐ฆtext[=<bool>]โ opens the file in text mode to force implicit line terminator conversions (Cygwin). ๐ฆnoinherit[=<bool>]โ does not keep this file open in a spawned process (Cygwin). ๐ฆcool-write[=<bool>]โ takes it easy when write fails withEPIPEorECONNRESETand logs the message with notice level instead of error. This prevents the log file from being filled with useless error messages when socat is used as a high volume server or proxy where clients often abort the connection. Use this option only with optionforkbecause otherwise it might cause socat to exit with code0even on failure. This option is deprecated, consider using optionchildren-shutupinstead. ๐end-close[=<bool>]โ changes the (address dependent) method of ending a connection to just close the file descriptors. This is useful when the connection is to be reused by or shared with other processes (example). Normally, socket connections will be ended withshutdown(2)which terminates the socket even if it is shared by multiple processes.close(2)"unlinks" the socket from the process but keeps it active as long as there are still links from other processes. Similarly, when an address of typeEXECorSYSTEMis ended, socat usually will explicitly kill the sub process. With this option, it will just close the file descriptors. ๐shut-none[=<bool>]โ changes the (address dependent) method of shutting down the write part of a connection to not do anything. ๐shut-down[=<bool>]โ changes the (address dependent) method of shutting down the write part of a connection toshutdown(fd, SHUT_WR). Is only useful with sockets. ๐shut-close[=<bool>]โ changes the (address dependent) method of shutting down the write part of a connection toclose(fd). ๐shut-null[=<bool>]โ when one address indicates EOF, socat will send a zero sized packet to the write channel of the other address to transfer the EOF condition. This is useful with UDP and other datagram protocols. Has been tested against netcat and socat with optionnull-eof. ๐ซงnull-eof[=<bool>]โ normally socat will ignore empty (zero size payload) packets arriving on datagram sockets, so it survives port scans. With this option socat interprets empty datagram packets as EOF indicator (seeshut-null). ๐ซงioctl-void=<request>โ callsioctl()with the request value as second argument andNULLas third argument. This option allows utilizing ioctls that are not explicitly implemented in socat. ๐ ๏ธioctl-int=<request>:<value>โ callsioctl()with the request value as second argument and the integer value as third argument. ๐ ๏ธioctl-intp=<request>:<value>โ callsioctl()with the request value as second argument and a pointer to the integer value as third argument. ๐ ๏ธioctl-bin=<request>:<value>โ callsioctl()with the request value as second argument and a pointer to the given data value as third argument. This data must be specified in<dalan>form. ๐ ๏ธioctl-string=<request>:<value>โ callsioctl()with the request value as second argument and a pointer to the given string as third argument.<dalan>form. ๐ ๏ธ
๐ธ NAMED option group ๐ธ
These options work on file system entries. Please note that, with UNIX domain client addresses, this means the bind entry, not the target/peer entry. See also options user, group, and mode. ๐
user-early=<user>โ changes the<user>(owner) of the file system entry before accessing it, using thechown()system call. This call might require root privilege. ๐group-early=<group>โ changes the<group>of the file system entry before accessing it, using thechown()system call. This call might require group membership or root privilege. ๐perm-early=<mode>โ changes the<mode>[mode_t]of the file system entry before accessing it, using thechmod()system call. This call might require ownership or root privilege. ๐unlink-early[=<bool>]โ unlinks (removes) the file before opening it and even before applyinguser-earlyetc. ๐๏ธunlink[=<bool>]โ unlinks (removes) the file before accessing it, but afteruser-earlyetc. ๐๏ธunlink-late[=<bool>]โ unlinks (removes) the file after opening it to make it inaccessible for other processes after a short race condition. ๐๏ธunlink-close[=<bool>]โ controls removal of the address's file system entry when closing the address. For named pipes, UNIX domain sockets, and the symbolic links of pty addresses, the default is remove (1); for created files, opened files, and generic opened files the default is keep (0). Setting this option to1removes the entry,0keeps it. No value means1. ๐๏ธ
โจ OPEN option group โจ
The OPEN group options allow setting flags with the open() system call. E.g., option creatโ sets the O_CREATflag. When the used address does not useopen()(e.g.STDIO), thefcntl(..., F_SETFL, ...)call is used instead. See also optionsappendandnonblock`. ๐
creat[=<bool>]โ creates the file if it does not exist (example). ๐dsync[=<bool>]โ blockswrite()calls until metainfo is physically written to media. ๐พexcl[=<bool>]โ with optioncreat, if file exists this is an error. โlargefile[=<bool>]โ on 32 bit systems, allows a file larger than2^31bytes. ๐noatime[=<bool>]โ sets theO_NOATIMEoptions, so reads do not change the access timestamp. โฐnoctty[=<bool>]โ does not make this file the controlling terminal. ๐ฅ๏ธnofollow[=<bool>]โ does not follow symbolic links. ๐nshare[=<bool>]โ does not allow sharing this file with other processes. ๐ซrshare[=<bool>]โ does not allow other processes to open this file for writing. ๐ซrsync[=<bool>]โ blockswrite()until metainfo is physically written to media. ๐พsync[=<bool>]โ blockswrite()until data is physically written to media. ๐พrdonly[=<bool>]โ opens the file for reading only. ๐wronly[=<bool>]โ opens the file for writing only. โ๏ธtrunc[=<bool>]โ truncates the file to size0during opening it. โ๏ธ
๐ซ REG and BLK option group ๐ซ
These options are usually applied to a UN*X file descriptor, but their semantics make sense only on a file supporting random access. ๐
seek=<offset>โ applies thelseek(fd, <offset>, SEEK_SET)(orlseek64) system call, thus positioning the file pointer absolutely to<offset>[off_t or off64_t]. Please note that a missing value defaults to1, not0. ๐ฏseek-cur=<offset>โ applies thelseek(fd, <offset>, SEEK_CUR)(orlseek64) system call, thus positioning the file pointer<offset>[off_t or off64_t]bytes relatively to its current position (which is usually0). Please note that a missing value defaults to1, not0. ๐ฏseek-end=<offset>โ applies thelseek(fd, <offset>, SEEK_END)(orlseek64) system call, thus positioning the file pointer<offset>[off_t or off64_t]bytes relatively to the files current end. Please note that a missing value defaults to1, not0. ๐ฏftruncate=<offset>โ runs theftruncate(fd, <offset>)system call (orftruncate64if your system has it), which chops the file off right at position<offset>[off_toroff64_t]. ๐ช Heads up bestie: if you leave the value off it defaults to 1, not 0. yeah. one.secrm[=<bool>]unrm[=<bool>]compr[=<bool>]fs-sync[=<bool>]immutable[=<bool>]fs-append[=<bool>]nodump[=<bool>]fs-noatime[=<bool>]journal-data[=<bool>]notail[=<bool>]dirsync[=<bool>]โ okay so this whole lil squad right here changes the non-standard file attributes, and only on operating systems and file systems that actually support that kind of thing โ think Linux withext2fsand its successors,xfs, orreiserfs. Go readman 1 chattrfor the tea on what each one does. โ ๏ธ And be aware: there can be a race condition between creating the file and applying these options. so like. timing is everything.
๐ง PIPE options ๐ง
These cuties get applied to pipes (fifos).
f-setpipe-sz=<int>setpipe=<int>โ sets how many bytes a pipe can buffer. If you write more than that, the writing process might block. And if you try to write more bytes in a singlewrite(), the writing process blocks and might never recover. ๐ so maybe don't do that.
๐ธ General address options ๐ธ
These ones work on all address types. They change some process properties โ and those get restored after the address is opened.
chdir=<filename>cd=<filename>โ changes the working directory. After the address opens, the master process switches back to the original working directory. Sub processes inherit the temporary setting though.umask=<mode>โ sets the process umask to<mode>[mode_t] before opening the address. Super handy when file system entries are getting created or when a shell or program is invoked. Usually you write the value as an octal number with a leading โ0โ. The process umask value gets inherited by child processes. ๐ซถ Note: umask is an inverted value โ so creating a file withumask=0026gives you permissions0640.
๐ PROCESS option group ๐
Options in this group change the process properties instead of just messing with one data channel. For EXEC and SYSTEM addresses, and for LISTEN and CONNECT type addresses with option fork, these options apply to the child processes instead of the main socat process.
chroot=<directory>โ does achroot()operation to<directory>after processing the address (example). This call might need root privilege.chroot-early=<directory>โ does achroot()operation to<directory>before opening the address. This call might need root privilege.setgid=<group>โ changes the primary<group>of the process after processing the address. This call might need root privilege. Please note that this option does not drop other group related privileges.setgid-early=<group>โ likesetgidbut performed before opening the address.setuid=<user>โ changes the<user>(owner) of the process after processing the address. This call might need root privilege. Please note that this option does not drop group related privileges. Check if optionsufits your needs better. ๐setuid-early=<user>โ likesetuidbut performed before opening the address.su=<user>โ changes the<user>(owner) and groups of the process after processing the address (example). This call might need root privilege.su-d=<user>โ short name forsubstuser-delayed. Changes the<user>(owner) and groups of the process after processing the address (example). The user and their groups are retrieved before a possiblechroot(). This call might need root privilege.setpgid=<pid_t>โ makes the process a member of the specified process group<pid_t>. If no value is given, or if the value is0or1, the process becomes leader of a new process group. slay.setsidโ makes the process the leader of a new session (example).netns=<net-namespace-name>โ before opening the address it tries to switch to the named network namespace. After opening the address it switches back to the previous namespace (example with TCP forwarder, example with virtual network connection). ๐ง Only on Linux; this option requires root and is experimental.
๐ READLINE option group ๐
These options apply to the readline address type.
history=<filename>โ reads and writes history from/to<filename>(example).nopromptโ since version1.4.0, socat by default tries to figure out a prompt โ which it then passes to the readline call โ by remembering the last incomplete line of the output. With this option, socat does not pass a prompt to readline, so it begins line editing in the first column of the terminal. โจnoecho=<pattern>โ specifies a regular pattern for a prompt that stops the following input line from being displayed on screen and from being added to the history. The prompt is defined as the text that was output to the readline address after the last newline character and before an input character was typed. The pattern is a regular expression, e.g."^[Pp]assword:.*$"or"([Uu]ser:|[Pp]assword:)". Seeregex(7)for details. (example) ๐prompt=<string>โ passes the string as prompt to the readline function. readline prints this prompt when stepping through the history. If this string matches a constant prompt issued by an interactive program on the other socat address, you get consistent look and feel. ๐
๐ฆ APPLICATION option group ๐ฆ
This group has options that work at the data level. Note that these options only apply to the "raw" data transferred by socat โ not to protocol data used by addresses like PROXY.
crโ converts the default line termination character NL (โ\nโ,0x0a) to/from CR (โ\rโ,0x0d) when writing/reading on this channel.crnlโ converts the default line termination character NL (โ\nโ,0x0a) to/from CRNL ("\r\n",0x0d0a) when writing/reading on this channel (example). Note: socat simply strips all CR characters.ignoreeofโ when EOF occurs on this channel, socat ignores it and tries to read more data (like"tail -f") (example). iconic behaviour tbh.readbytes=<bytes>โ socat reads only so many bytes from this address (the address provides only so many bytes for transfer and pretends to be at EOF afterwards). Must be greater than0.lockfile=<filename>โ if lockfile exists, exits with error. If lockfile does not exist, creates it and continues, unlinks lockfile on exit.waitlock=<filename>โ if lockfile exists, waits until it disappears. When lockfile does not exist, creates it and continues, unlinks lockfile on exit.escape=<int>โ specifies the numeric code of a character that triggers EOF on the input stream. Itโs useful with a terminal in raw mode (example).
๐ SOCKET option group ๐
These options are meant for all kinds of sockets, e.g. IP or UNIX domain. Most get applied with a setsockopt() call.
bind=<sockname>โ binds the socket to the given socket address using thebind()system call. The form of<sockname>depends on the socket domain:IP4andIP6allow the form[hostname|hostaddress][:(service|port)](example),VSOCKallows the form[cid][:(port)]. See also:unix-bind-tempnameconnect-timeout=<seconds>โ aborts the connection attempt after<seconds>[timeval] with error status.so-bindtodevice=<interface>โ binds the socket to the given<interface>. This option might require root privilege.broadcastโ for datagram sockets, allows sending to broadcast addresses and receiving packets addressed to broadcast addresses.debugโ enables socket debugging.dontrouteโ only communicates with directly connected peers, does not use routers.keepaliveโ enables sending keepalives on the socket.linger=<seconds>โ blocksshutdown()orclose()until data transfers have finished or the given timeout [int] expired.oobinlineโ places out-of-band data in the input data stream.priority=<priority>โ sets the protocol defined<priority>[<int>] for outgoing packets.rcvbuf=<bytes>โ sets the size of the receive buffer after thesocket()call to<bytes>[int]. With TCP sockets, this value corresponds to the socketโs maximal window size.rcvbuf-late=<bytes>โ sets the size of the receive buffer when the socket is already connected, to<bytes>[int]. With TCP sockets, this value corresponds to the socketโs maximal window size.so-rcvtimeo=<time>,rcvtimeo=<time>โ specifies the time [int] untilrecv(),read()etc. functions timeout when no data is received. Note that in the transfer phase socat only calls these functions whenselect()has reported that data is available. However this option is useful withDTLSaddresses to timeout during connection negotiation.so-sndtimeo=<time>,sndtimeo=<time>โ likeso-rcvtimeo, but forsend. Not usecase known. ๐ญrcvlowat=<bytes>โ specifies the minimum number of received bytes [int] until the socket layer will pass the buffered data to socat.reuseaddr[=[0|1]]โ allows other sockets to bind to an address even if parts of it (e.g. the local port) are already in use by socat. With version1.8.0, this socket option is set automatically forTCP LISTENaddresses. If you prefer the system default (no relatedsetsockopt(...SO_REUSEADDR...)call at all), use the formreuseaddr=. (example).sndbuf=<bytes>โ sets the size of the send buffer after thesocket()call to<bytes>[int].sndbuf-late=<bytes>โ sets the size of the send buffer when the socket is connected, to<bytes>[int].sndlowat=<bytes>โ specifies the minimum number of bytes in the send buffer until the socket layer will send the data, to<bytes>[int].protocol-family=<string>,pf=<string>โ pf is short for protocol family, and it's also called the communication domain or the address family, iykyk ๐ . This option forces the use of a specific IP version or protocol. <string> can be a plain number, or something like"ip4"(which means 2) or"ip6"(which means 10). Whatever value you end up with gets used as the first argument to thesocket()orsocketpair()calls, and it also goes into theai_familyfield in thegetaddrinfo()hints. Heads up bestie: this option affects address resolution and the syntax you're required to use forbindandrangeoptions. So it's not just a lil cosmetic thing, ok? ๐socktype=<type>โ sets the type of the socket, given as the second argument to thesocket()orsocketpair()calls, to <type> [int]. Address resolution is not affected by this one. Under Linux,1means stream oriented socket,2means datagram socket,3means raw socket, and5seqpacket (stream keeping packet boundaries). Datagrams are lowkey useful when you want to keep packet boundaries โจ.protocolโ sets the protocol of the socket, given as the third argument to thesocket()orsocketpair()calls, to <protocol> [int]. Address resolution is not affected by this option either.6means TCP,17means UDP. Periodt ๐.reuseportโ sets theSO_REUSEPORTsocket option. slay.so-timestampโ sets theSO_TIMESTAMPsocket option. This enables receiving and logging of timestamp ancillary messages โฐ.setsockopt=<level>:<optname>:<optval>โ invokessetsockopt()for the socket with the given parameters.level[int] is used as the second argument tosetsockopt()and specifies the layer, e.g.SOL_TCPfor TCP (6on Linux), orSOL_SOCKETfor the socket layer (1on Linux).optname[int] is the third argument tosetsockopt()and tells which socket option is to be set. For the actual numbers you might have to look up the appropriate include files of your system ๐. For the 4th and 5thsetsockopt()parameters,value[dalan] specifies an arbitrary sequence of bytes that are passed to the function per pointer, with the automatically derived length parameter.setsockopt-int=<level>:<optname>:<optval>โ likesetsockopt, but <optval> is a pointer toint[int] ๐ง .setsockopt-listen=<level>:<optname>:<optval>โ likesetsockopt, but for listen type addresses it is applied to the listening socket instead of the connected socket ๐.setsockopt-string=<level>:<optname>:<optval>โ likesetsockopt, but <optval> is a string. This string is passed to the function with a trailing null character, and the length parameter is automatically derived from the data ๐ค.setsockopt-socket=<level>:<optname>:<optval>โ likesetsockopt, but is applied to the socket before other operations (bind(),connect(),accept(), ...). Early bird energy ๐ฆ.setsockopt-connected=<level>:<optname>:<optval>โ likesetsockopt, but is applied only when the socket has been connected by aconnect()orlisten()call ๐.
๐ UNIX option group ๐
These options apply to UNIX domain based addresses ๐ฆ.
bind-tempname[=/tmp/pre-XXXXXX],unix-bind-tempname[=/tmp/pre-XXXXXX]โ binds to a random path or random address (on abstract namespace sockets). This is useful with datagram client addresses (SENDTO, orCLIENT) that are opened in child processes forked off from a common parent process where the child processes cannot have differentbindoptions. In the path,X's get replaced with a random character sequence similar totempnam(3)๐ฒ. When no argument is given socat takes a default like/tmp/fileXXXXXX.unix-tightsocklen[=(0|1)]โ on socket operations, pass a socket address length that does not include the wholestruct sockaddr_unrecord but (besides other components) only the relevant part of the filename or abstract string. Default is1๐ซถ.
๐ IP4 and IP6 option groups ๐
These options can be used with IPv4 and IPv6 based sockets, bestie ๐.
tos=<tos>โ sets the TOS (type of service) field of outgoing packets to <tos> [byte] (see RFC 791) โจ.ttl=<ttl>โ sets the TTL (time to live) field of outgoing packets to <ttl> [byte] โณ.ip-options=<data>โ sets IP options like source routing ๐ฃ๏ธ. Must be given in binary form, recommended format is a leading"x"followed by an even number of hex digits. This option may be used multiple times, and data are appended. E.g., to connect to host10.0.0.1via some gateway using a loose source route, use the gateway as address parameter and set a loose source route using the optionip-options=x8307040a000001. IP options are defined in RFC 791 ๐.ip-mtu-discover=<0|1|2>,mtudiscover=<0|1|2>โ takes0,1,2to never, want, or always use path MTU discover on the IPv4 socket ๐.ip-pktinfoโ sets theIP_PKTINFOsocket option. This enables receiving and logging of ancillary messages containing destination address and interface (Linux) (example) ๐ฆ.ip-recverrโ sets theIP_RECVERRsocket option. This enables receiving and logging of ancillary messages containing detailed error information ๐.ip-recvoptsโ sets theIP_RECVOPTSsocket option. This enables receiving and logging of IP options ancillary messages (Linux, *BSD) ๐.ip-recvtosโ sets theIP_RECVTOSsocket option. This enables receiving and logging of TOS (type of service) ancillary messages (Linux) ๐ธ.ip-recvttlโ sets theIP_RECVTTLsocket option. This enables receiving and logging of TTL (time to live) ancillary messages (Linux, *BSD) โฐ.ip-recvdstaddrโ sets theIP_RECVDSTADDRsocket option. This enables receiving and logging of ancillary messages containing destination address (*BSD) (example) ๐ฌ.ip-recvifโ sets theIP_RECVIFsocket option. This enables receiving and logging of interface ancillary messages (*BSD) (example) ๐ฐ๏ธ.ip-add-membership=<multicast-address:interface-address>ip-add-membership=<multicast-address:interface-name>ip-add-membership=<multicast-address:interface-index>ip-add-membership=<multicast-address:interface-address:interface-name>ip-add-membership=<multicast-address:interface-address:interface-index>
All five of those make the socket a member of the specified multicast group ๐ฏ. This only works for IPv4, see ipv6-join-group for the IPv6 variant. The option takes the IP address of the multicast group and info about the desired network interface. The most common syntax is the first one, while the others are only available on systems that provide struct mreqn (Linux). The indices of active network interfaces can be shown using the utility procan ๐.
ip-add-source-membership=<multicast-address:interface-address:source-address>โ makes the socket a member of the specified multicast group for the specified source, i.e. only multicast traffic from this address is to be delivered ๐ฏ. This only works for IPv4, seeipv6-join-source-groupfor the IPv6 variant. The option takes the IP address of the multicast group, the IP address of the desired network interface and the source IP address of the multicast traffic.ipv6-join-group=<multicast-address:interface-name>ipv6-join-group=<multicast-address:interface-index>
Both of these make the socket a member of the specified multicast group ๐. This only works for IPv6, see ip-add-membership for the IPv4 variant. The option takes the IP address of the multicast group and info about the desired network interface. The indices of active network interfaces can be shown using the utility procan ๐.
ipv6-join-source-group=<multicast-address:interface-name:source-address>ipv6-join-source-group=<multicast-address:interface-index:source-address>
Both of these make the socket a member of the specified multicast group for the specified source, i.e. only multicast traffic from this address is to be delivered ๐ฏ. This only works for IPv6, see ip-add-source-membership for the IPv4 variant. The option takes the IP address of the multicast group, info about the desired network interface and the source IP address of the multicast traffic. The indices of active network interfaces can be shown using the utility procan ๐.
ip-multicast-if=<hostname>โ specifies hostname or address of the network interface to be used for multicast traffic ๐ฐ๏ธ.ip-multicast-loop[=<bool>],mcloop[=<bool>]โ specifies if outgoing multicast traffic should also loop back to the interface ๐.ip-multicast-ttl=<byte>โ sets the TTL used for outgoing multicast traffic. Default is1โณ.ip-transparentโ sets theIP_TRANSPARENTsocket option. This option might require root privilege ๐. No cap, respect the permissions bestie.
๐ Resolver options ๐
These options temporarily change the behaviour of hostname resolution. The options of form ai-* affect behaviour of the getaddrinfo() function that includes /etc/hosts and NIS based lookups ๐.
The addresses of form res-* only affect DNS lookups, and only when the result is not cached in nscd. These options might not work on all operating systems or libc implementations ๐.
ai-addrconfig[=0|1]addrconfig[=0|1]
Sets or unsets the AI_ADDRCONFIG flag to prevent name resolution to address families that are not available on the computer (e.g. IPv6) ๐ซ. Default value is 1 in case the resolver does not get an address family hint from Socat address or defaults.
ai-passive[=0|1]passive[=0|1]
Sets or unsets the AI_PASSIVE flag for getaddrinfo() calls. Default is 1 for LISTEN, RECV, and RECVFROM type addresses, and with bind option ๐ค.
ai-v4mapped[=0|1]v4mapped[=0|1]
Sets or unsets the AI_V4MAPPED flag for getaddrinfo(). With socat addresses requiring IPv6 addresses, this resolves IPv4 addresses to the appropriate IPv6 address [::ffff:*:*] ๐. For IPv6 socat addresses, the default is 1.
ai-all[=0|1]โ sets or unsets theAI_ALLflag forgetaddrinfo()โจ.res-debugres-aaonlyres-usevcres-primaryres-igntcres-recurseres-defnamesres-stayopen
Yeah bestie, these are just listed here with no extra blurb attached to them โ they're simply vibing in the list ๐ ๐ฆ.
res-dnsrch โ okay so these set the matching resolver (a.k.a. name resolution) option flags, bestie. Slap =0 on the end to clear a default option. Wanna know more? Go read resolver(5), it's all there. Socat restores the old values after it finishes the open phase of the address, so these options are valid just for the address they're applied to, no carryover, periodt. Heads up though: these flags only affect DNS resolution, not hosts- or NIS-based name resolution, and they do absolutely nothing when (g)libc pulls the results out of nscd. ๐
res-retrans=<int>โ sets the retransmission time interval of the DNS resolver (this rides on an undocumented feature, so, yk).res-retry=<int>โ sets the number of retransmits of the DNS resolver (also based on an undocumented feature).res-nsaddr=<ipaddr>[:<port>]โ tries to overwrite the nameserver settings loaded from/etc/resolv.confby writing that given IPv4 address into the undocumented_res:nsaddr_list[0]field./etc/hostsis still checked by the resolver. โ ๏ธ Please note that glibc's nscd is always queried first when it's running, so don't come for me if it ignores you.
โจ IP6 option group โจ
These options can only be used on IPv6-based sockets, no exceptions. If you want the ones that work on both IPv4 and IPv6 sockets, go look at the IP options instead. ๐ฆ
ipv6only[=<bool>]โ sets theIPV6_V6ONLYsocket option. If it's0, the TCP stack will also accept connections using the IPv4 protocol on the same port. The default is system dependent (so like, don't @ me).ipv6-recvdstoptsโ sets theIPV6_RECVDSTOPTSsocket option. This enables receiving and logging of ancillary messages containing the destination options.ipv6-recvhoplimitโ sets theIPV6_RECVHOPLIMITsocket option. Enables receiving and logging of ancillary messages containing the hoplimit.ipv6-recvhopoptsโ sets theIPV6_RECVHOPOPTSsocket option. Enables receiving and logging of ancillary messages containing the hop options.ipv6-recvpktinfoโ sets theIPV6_RECVPKTINFOsocket option. Enables receiving and logging of ancillary messages containing destination address and interface.ipv6-unicast-hops=link(TYPE_INT)(<int>)โ sets theIPV6_UNICAST_HOPSsocket option. This sets the hop count limit (TTL) for outgoing unicast packets.ipv6-recvrthdrโ sets theIPV6_RECVRTHDRsocket option. Enables receiving and logging of ancillary messages containing routing information.ipv6-tclassโ sets theIPV6_TCLASSsocket option. This sets the transfer class of outgoing packets.ipv6-recvtclassโ sets theIPV6_RECVTCLASSsocket option. Enables receiving and logging of ancillary messages containing the transfer class.ipv6-multicast-loop[=<bool>],mcloop6[=<bool>]โ specifies if outgoing multicast traffic should also loop back to the interface.ipv6-mtu-discover=<0|1|2>,mtudiscover6=<0|1|2>โ takes0,1, or2to never, want, or always use path MTU discover on the IPv6 socket.
๐ฅ TCP option group ๐ฅ
These options may be applied to TCP sockets. Under the hood they work by invoking setsockopt() with the appropriate parameters. Very demure, very mindful.
corkโ doesn't send packets smaller than MSS (maximal segment size).defer-acceptโ while listening, accepts connections only when data from the peer arrived.keepcnt=<count>โ sets the number of keepalives before shutting down the socket to<count>[int].keepidle=<seconds>โ sets the idle time before sending the first keepalive to<seconds>[int].keepintvl=<seconds>โ sets the interval between two keepalives to<seconds>[int].linger2=<seconds>โ sets the time to keep the socket in FIN-WAIT-2 state to<seconds>[int].mss=<bytes>โ sets the MSS (maximum segment size) after thesocket()call to<bytes>[int]. This value is then proposed to the peer with the SYN or SYN/ACK packet (example).mss-late=<bytes>โ sets the MSS of the socket after connection has been established to<bytes>[int].nodelayโ turns off the Nagle algorithm for measuring the RTT (round trip time).rfc1323โ enables RFC1323 TCP options: TCP window scale, round-trip time measurement (RTTM), and protect against wrapped sequence numbers (PAWS) (AIX).stdurgโ enables RFC1122 compliant urgent pointer handling (AIX).syncnt=<count>โ sets the maximal number of SYN retransmits during connect to<count>[int].md5sigโ enables generation of MD5 digests on the packets (FreeBSD).nooptโ disables use of TCP options (FreeBSD, MacOSX).nopushโ sets theTCP_NOPUSHsocket option (FreeBSD, MacOSX).sack-disableโ disables use of the selective acknowledge feature (OpenBSD).signature-enableโ enables generation of MD5 digests on the packets (OpenBSD).abort-threshold=<milliseconds>โ sets the time to wait for an answer of the peer on an established connection (HP-UX).conn-abort-threshold=<milliseconds>โ sets the time to wait for an answer of the server during the initial connect (HP-UX).keepinitโ sets the time to wait for an answer of the server duringconnect()before giving up. Value in half seconds, default is150(75s) (Tru64).pawsโ enables the "protect against wrapped sequence numbers" feature (Tru64).sackenaโ enables selective acknowledge (Tru64).tsoptenaโ enables the time stamp option that allows RTT recalculation on existing connections (Tru64).
๐ UDP option group ๐
This option may be applied to UDP datagram sockets.
udp-ignore-peerport>โ Address UDP-DATAGRAM expects incoming responses to come from the port specified in its second parameter. With this option, it accepts packets coming from any port. ๐
๐ UDPLITE option group ๐
These options may be applied to UDPLITE addresses:
udplite-send-cscovโ sets the number of bytes for which the checksum is calculated and sent ("checksum coverage").udplite-recv-cscovโ sets the number of bytes for which the checksum is checked ("checksum coverage").
๐ง SCTP option group ๐ง
These options may be applied to SCTP stream sockets.
sctp-nodelayโ sets theSCTP_NODELAYsocket option that disables the Nagle algorithm.sctp-maxseg=<bytes>โ sets theSCTP_MAXSEGsocket option to<bytes>[int]. This value is then proposed to the peer with the SYN or SYN/ACK packet.
๐ธ DCCP option group ๐ธ
These options may be applied to DCCP sockets.
dccp-set-ccid=<int>ccid=<int>โ selects the desired congestion control mechanism (CCID).
๐ UDP, TCP, SCTP, DCCP, and UDPLITE option group ๐
Here we find options that are related to the network port mechanism and thus can be used with UDP, TCP, SCTP, DCCP, and UDP-Lite client and server addresses. The whole squad, fr fr. ๐ซถ
sourceport=<port>โ for outgoing (client) connections, it sets the source<port>using an extrabind()call. With TCP or UDP listen addresses, socat immediately shuts down the connection if the client does not use this sourceport. UDP-RECV, UDP-RECVFROM, UDP-SENDTO, and UDP-DATAGRAM addresses ignore the packet when it does not match. (example).lowportโ outgoing (client) connections with this option use an unused random source port between640and1023incl. On UNIX class operating systems, this requires root privilege, and thus indicates that the client process is authorized by local root. TCP and UDP listen addresses with this option immediately shut down the connection if the client does not use a sourceport <=1023. This mechanism can provide limited authorization under some circumstances.
๐ SOCKS option group ๐
When you're using SOCKS type addresses, some socks-specific options can be set.
socksport=<tcp service>โ overrides the default"socks"service or port1080for the socks server port with<TCP service>.socksuser=<user>โ sends the<user>[string] in the username field to the socks server. Default is the actual user name ($LOGNAMEor$USER) (example).sockspass=<string>โ sends the given password [string] onusername,passwordauthentication to the socks5 server.
โญ HTTP option group โญ
Options that can be provided with HTTP type addresses. The only HTTP address currently implemented is proxy-connect. Ngl, that's it.
http-version=<string>โ changes the default"1.0"that is sent to the server in the initial HTTP request. Currently it has no other effect, in particular it does not provide any means to send aHostheader.proxyport=<TCP service>โ overrides the default HTTP proxy port8080with<TCP service>.ignorecrโ the HTTP protocol requires the use of CR+NL as line terminator. When a proxy server violates this standard, socat might not understand its answer. This option directs socat to interpret NL as line terminator and to ignore CR in the answer. Nevertheless, socat sends CR+NL to the proxy. (so the proxy gets the correct thing, it's just socat being forgiving on the way back ๐)proxy-authorization=<username>:<password>โ provide"basic"authentication to the proxy server. The argument to the option is used with a"Proxy-Authorization: Basic"header in base64 encoded form.
โ ๏ธ Note: username and password are visible for every user on the local machine in the process list; username and password are transferred to the proxy server unencrypted (base64 encoded) and might be sniffed. Be so careful bestie, seriously. ๐ญ
proxy-authorization-file=<filename>โ like optionproxy-authorization, but the credentials are read from the file and therefore not visible in the process list. Slay, security.resolveโ per default, socat sends to the proxy aCONNECTrequest containing the target hostname. With this option, socat resolves the hostname locally and sends the IP address. Please note that, according to RFC 2396, only name resolution to IPv4 addresses is implemented.
๐ RANGE option group ๐
These options check if a connecting client should be granted access. They can be applied to listening and receiving network sockets. The tcp-wrappers options fall into this group too.
range=<address-range>โ after socat accepts a connection, it checks whether the peer is inside your range. For IPv4,<address-range>looks likeaddress/bits, e.g.10.0.0.0/8, or likeaddress:mask, e.g.10.0.0.0:255.0.0.0(there's an example for this). For IPv6 it's[ip6-address]/bits, e.g.[::1]/128. If the client address does not match, socat straight up refuses the connection attempt, throws a warning, and keeps on listening/receiving. not the vibe you wanted? it's literally the point ๐tcpwrap[=<name>]โ uses Wietse Venema's libwrap (tcpd) library to decide whether the client is allowed to connect. The config files are/etc/hosts.allowand/etc/hosts.denyby default โ peepman 5 hosts_accessfor the deets. The optional<name>(type string) gets passed to the wrapper functions as the daemon process name (there's an example). If you leave it out, the basename of socat's invocation (argv[0]) is passed instead. And bestie, listen: if bothtcpwrapandrangeare applied to an address, both conditions have to be fulfilled to let the connection through. double gatekeeping, iconic honestly ๐allow-table=<filename>โ takes the file you name instead of/etc/hosts.allow.deny-table=<filename>โ takes the file you name instead of/etc/hosts.deny.tcpwrap-etc=<directoryname>โ looks forhosts.allowandhosts.denyin the directory you give. This gets overridden by the optionshosts-allowandhosts-deny.
๐ง LISTEN option group
Options specific to listening sockets. the ones that sit there and wait for the phone to ring ๐
backlog=<count>โ sets the backlog value that gets passed to thelisten()system call to<count>[int]. Default is5.accept-timeout=<seconds>โ stops waiting for a connection after<seconds>[timeval], and exits with error status. clock's ticking bestie โฐ
๐ถ CHILD option group
Addresses of LISTEN and CONNECT type take the fork option to handle multiple connections via child processes.
forkโ after establishing a connection, socat handles its channel in a child process and keeps the parent process attempting to produce more connections, either by listening or by connecting in a loop (there's an example).
OPENSSL-CONNECT and OPENSSL-LISTEN differ in when they actually fork off the child: OPENSSL-LISTEN forks before the SSL handshake, while OPENSSL-CONNECT forks afterwards. The retry and forever options are not inherited by the child process.
On some operating systems (e.g. FreeBSD) this option does not work for UDP-LISTEN addresses. FreeBSD girlies, you've been warned ๐
max-children=<count>โ limits the number of concurrent child processes[int]. Default is no limit. populate the whole server, no cap ๐ซถchildren-shutup[=1|2|..]โ decreases the severity of log messages produced by child processes. For example, with value1notices are logged as info (or dropped, depending on option-dX), and errors are logged as warnings but still cause termination of the child process. This option is meant to reduce logging of high volume servers or proxies. It succeeds the optioncool-write. shhh bestie, the children are sleeping ๐คซ
๐ EXEC option group
Options for addresses that invoke a program.
path=<string>โ overrides thePATHenvironment variable used to search for the program, using<string>. This$PATHvalue is effective in the child process too.loginโ prefixesargv[0]for theexecvp()call with'-', thus making a shell behave as a login shell.
๐ด FORK option group
EXEC or SYSTEM addresses invoke a program using a child process and transfer data between socat and the program. The interprocess communication mechanism can be influenced with the following options.
Per default, a socketpair() is created and assigned to stdin and stdout of the child process, while stderr is inherited from the socat process, and the child process uses file descriptors 0 and 1 for communicating with the main socat process. default setup, no notes โจ
noforkโ does not fork a subprocess for executing the program; instead it callsexecvp()orsystem()directly from the actual socat instance. This avoids the overhead of another process between the program and its peer, but introduces a lot of restrictions:- this option can only be applied to the second socat address.
- it cannot be applied to a part of a dual address.
- the first socat address cannot be
OPENSSLorREADLINE - socat options
-b,-t,-D,-l,-v,-xbecome useless - for both addresses, options
ignoreeof,cr, andcrnlbecome useless - for both addresses, address specific end/shutdown handling (e.g., graceful socket shutdown) and related options become useless
- for the second address (the one with option
nofork), optionsappend,cloexec,flock,user,group,mode,nonblock,perm-late,setlk, andsetpgidcannot be applied. Some of these could be used on the first address though.
okay bestie this one has RULES. read the list twice, no skipping ๐
pipesโ creates a pair of unnamed pipes for interprocess communication instead of a socket pair.openptyโ establishes communication with the sub process using a pseudo terminal created withopenpty()instead of the default (socketpairorptmx).ptmxโ establishes communication with the sub process using a pseudo terminal created by opening/dev/ptmxor/dev/ptcinstead of the default (socketpair).ptyโ establishes communication with the sub process using a pseudo terminal instead of a socket pair. Creates the pty with an available mechanism. Ifopenptyandptmxare both available, it usesptmxbecause this is POSIX compliant (there's an example). POSIX compliant? we love a rule-follower ๐cttyโ makes the pty the controlling tty of the sub process (there's an example).stderrโ directsstderrof the sub process to its output channel by makingstderradup()ofstdout(there's an example).fdin=<fdnum>โ assigns the sub process's input channel to its file descriptor<fdnum>instead ofstdin(0). The program started from the subprocess has to use this fd for reading data from socat (there's an example).fdout=<fdnum>โ assigns the sub process's output channel to its file descriptor<fdnum>instead ofstdout(1). The program started from the subprocess has to use this fd for writing data to socat (there's an example).sighup,sigint,sigquitโ has socat pass signals of this type to the sub process. If no address has this option, socat terminates on these signals. signal forwarding, bestie behaviour fr fr ๐ซถ
๐ Options for address SHELL
shell=<filename>โ overwrites the default shell with the named executable, e.g./bin/dash. Also sets theSHELLenvironment variable.
๐ฅ๏ธ TERMIOS option group
For addresses that work on a tty (e.g., stdio, file:/dev/tty, exec:...,pty), the terminal parameters defined in the UN*X termios mechanism are made available as address option parameters.
heads up bestie: changes to the parameters of your interactive terminal remain effective after socat's termination, so you might have to enterresetorstty sanein your shell afterwards. ๐ญ not your terminal being permanently changed, no ma'am
For EXEC and SYSTEM addresses with option PTY, these options apply to the pty by the child processes.
b0โ disconnects the terminal.b19200โ sets the serial line speed to 19200 baud. Some other rates are possible; use something likesocat -hh |grep โ b[1-9]โto find all speeds supported by your implementation.
Note: on some operating systems, these options may not be available. Use ispeed or ospeed instead.
echo[=<bool>]โ enables or disables local echo.icanon[=<bool>]โ sets or clears canonical mode, enabling line buffering and some special characters.rawโ sets raw mode, thus passing input and output almost unprocessed. This option is obsolete, use optionrawerorcfmakerawinstead. obsolete alert, she's retired ๐rawerโ makes the terminal rawer than therawoption. This option implicitly turns off echo. (there's an example).cfmakerawโ sets raw mode by invokingcfmakeraw()or by simulating this call. This option implicitly turns off echo.ignbrk[=<bool>]โ ignores or interprets the BREAK character (e.g.,^C)brkint[=<bool>]bs0bs1bsdly=<0|1>clocal[=<bool>]cr0,cr1,cr2,cr3โ sets the carriage return delay to0,1,2, or3, respectively.0means no delay, the other values are terminal dependent.crdly=<0|1|2|3>cread[=<bool>]crtscts[=<bool>]cs5,cs6,cs7,cs8โ sets the character size to 5, 6, 7, or 8 bits, respectively.csize=<0|1|2|3>cstopb[=<bool>]โ sets two stop bits, rather than one.dsusp=<byte>โ sets the value for theVDSUSPcharacter that suspends the current foreground process and reactivates the shell (all except Linux).echoctl[=<bool>]โ echos control characters in hat notation (e.g.^A)echoe[=<bool>]echok[=<bool>]echoke[=<bool>]echonl[=<bool>]echoprt[=<bool>]eof=<byte>eol=<byte>eol2=<byte>erase=<byte>discard=<byte>ff0ff1ffdly[=<bool>]flusho[=<bool>]hupcl[=<bool>]icrnl[=<bool>]iexten[=<bool>]igncr[=<bool>]ignpar[=<bool>]imaxbel[=<bool>]inlcr[=<bool>]inpck[=<bool>]intr=<byte>isig[=<bool>]ispeed=<unsigned-int>โ set the baud rate for incoming data on this line. See also:ospeed,b19200istrip[=<bool>]iuclc[=<bool>]ixany[=<bool>]ixoff[=<bool>]ixon[=<bool>]kill=<byte>lnext=<byte>min=<byte>nl0โ sets the newline delay to 0.nl1nldly[=<bool>]noflsh[=<bool>]ocrnl[=<bool>]ofdel[=<bool>]ofill[=<bool>]olcuc[=<bool>]onlcr[=<bool>]onlret[=<bool>]onocr[=<bool>]opost[=<bool>]โ enables or disables output processing; e.g., converts NL to CR-NL.ospeed=<unsigned-int>โ set the baud rate for outgoing data on this line. See also:ispeed,b19200parenb[=<bool>]โ enable parity generation on output and parity checking for input.parmrk[=<bool>]parodd[=<bool>]pendin[=<bool>]quit=<byte>reprint=<byte>saneโ brings the terminal to something like a useful default state. the "bestie, calm down" button ๐งstart=<byte>stop=<byte>susp=<byte>swtc=<byte>tab0tab1tab2tab3tabdly=<unsigned-int>time=<byte>tostop[=<bool>]vt0vt1vtdly[=<bool>]werase=<byte>xcase[=<bool>]xtabs
๐ i-pop-all
i-pop-allโ with UNIX System V STREAMS, removes all drivers from the stack. streams girlies, this one's for you ๐i-push=<string>โ ok so with UNIX System V STREAMS, this pushes the driver (module) with the given name (the string) onto the stack ๐ . Like, for example, to make sure that a character device on Solaris supportstermiosetc, you'd use these options:
i-pop-all,i-push=ptem,i-push=ldterm,i-push=ttcompat
termios-setflags=<word>:<flags>,setflags=<word>:<flags>โ sets onec_*flagword ofstruct termiosto the given value. Word0isc_iflag, word3isc_lflagโจ.
๐ PTY option group ๐
These options are intended for use with the pty address type, bestie.
link=<filename>โ generates a symbolic link that points to the actual pseudo terminal (pty) ๐ฆ. This might help solve the problem that ptys get generated with more or less unpredictable names, which makes it difficult to directly access the socat-generated pty automatically. With this option, the user can specify a "fix" point in the file hierarchy that helps him access the actual pty (example). Beginning with socat version1.4.3, the symbolic link is removed when the address is closed (but see optionunlink-close) ๐.wait-slaveโ blocks the open phase until a process opens the slave side of the pty ๐. Usually, socat continues after generating the pty with opening the next address or with entering the transfer loop. With thewait-slaveoption, socat waits until some process opens the slave side of the pty before continuing. This option only works if the operating system provides thepoll()system call. And it depends on an undocumented behaviour of pty's, so it does not work on all operating systems ๐ญ. It has successfully been tested on Linux, FreeBSD, NetBSD, and on Tru64 withopenpty.pty-interval=<seconds>โ when thewait-slaveoption is set, socat periodically checks the HUP condition usingpoll()to find if the pty's slave side has been opened. The default polling interval is1sโฐ. Use thepty-intervaloption [timeval] to change this value.sitout-eio=<timeval>โ theloginprogram in Linux closes its tty/pty and reopens it for security reasons ๐. During this time the pty master would getEIOon I/O operations and might terminate. With this option socat toleratesEIOfor the specified time. Please note that in this state socat blocks traffic in both directions, even when it is not related to this channel ๐.tiocswinsz=<col>:<row>,tiocswinsz=<col>:<row>โ sets the size of a pseudo terminal ๐ธ.
๐ฅ OPENSSL option group ๐ฅ
These options apply to the openssl and openssl-listen address types. Periodt.
cipher=<cipherlist>โ specifies the list of ciphers that may be used for the connection ๐. See the man page ofciphers, sectionCIPHER LIST FORMAT, for detailed information about syntax, values, and default of <cipherlist>. Several cipher strings may be given, separated by':'. Some simple cipher strings:3DESโ uses a cipher suite with triple DES.MD5โ uses a cipher suite with MD5.aNULLโ uses a cipher suite without authentication.NULLโ does not use encryption ๐.HIGHโ uses a cipher suite with "high" encryption. Note that the peer must support the selected property, or the negotiation will fail ๐ฌ.
method=<ssl-method>โ this option is based on deprecated functions and is only available when socat was build with option--with-openssl-method๐ฉ. Use optionmin-proto-versionand maybemax-proto-versioninstead. Sets the protocol version to be used. Valid strings (not case sensitive) are:SSL2โ select SSL protocol version 2.SSL3โ select SSL protocol version 3.SSL23โ select the best available SSL or TLS protocol.TLS1โ select TLS protocol version 1.TLS1.1โ select TLS protocol version 1.1.TLS1.2โ select TLS protocol version 1.2. When this option is not provided OpenSSL negotiates the method with its peer.
openssl-min-proto-version=<string>,min-proto-version=<string>โ this option tells OpenSSL to use this or a later SSL/TLS protocol version and refuses to accept a lower/older protocol ๐ . Valid syntax is:SSL2โ select SSL protocol version 2.SSL3โ select SSL protocol version 3.TLS1TLS1.0โ select TLS protocol version 1.TLS1.1โ select TLS protocol version 1.1.TLS1.2โ select TLS protocol version 1.2.TLS1.3โ select TLS protocol version 1.3.
openssl-max-proto-version=<string>,max-proto-version=<string>โ this option is similar tomin-proto-version, however, it disallows use of a higher protocol version ๐ซ. Useful for testing the peer.verify[=<bool>]โ controls check of the peer's certificate. Default is1(true) โ .
Disabling verify might open your socket for everyone, making the encryption useless! ๐ Not the vibe.
cert=<filename>โ specifies the file with the certificate and private key for authentication ๐. The certificate must be in OpenSSL format (*.pem). Withopenssl-listen, use of this option is strongly recommended. Except with cipheraNULL, "no shared ciphers" error will occur when no certificate is given ๐ญ.key=<filename>โ specifies the file with the private key. The private key may be in this file or in the file given with thecertoption. The party that has to proof that it is the owner of a certificate needs the private key ๐๏ธ.dhparams=<filename>โ specifies the file with the Diffie Hellman parameters. These parameters may also be in the file given with thecertoption, in which case thedhparamsoption is not needed ๐.cafile=<filename>โ specifies the file with the trusted (root) authority certificates ๐ณ. The file must be in PEM format and should contain one or more certificates. The party that checks the authentication of its peer trusts only certificates that are in this file.capath=<dirname>โ specifies the directory with the trusted (root) certificates. The directory must contain certificates in PEM format and their hashes (see OpenSSL documentation) ๐.egd=<filename>โ on some systems, openssl requires an explicit source of random data ๐ฒ. Specify the socket name where an entropy gathering daemon like egd provides random data, e.g./dev/egd-pool.openssl-maxfraglen=<int>,maxfraglen=<int>โ for client connections, make a Max Fragment Length Negotiation Request to the server to limit the maximum size fragment the server will send to us ๐. Supported lengths are:512,1024,2048, or4096. Note that this option is not applicable forOPENSSL-LISTEN.openssl-maxsendfrag=<int>,maxsendfrag=<int>โ limit the maximum size of the fragment we will send to the other side ๐ค. Supported length range:512-16384. Note that underOPENSSL-LISTEN, the maximum fragment size may be further limited by the client's Maximum Fragment Length Negotiation Request, if it makes one.pseudoโ on systems where openssl cannot find an entropy source and where no entropy gathering daemon can be utilized, this option activates a mechanism for providing pseudo entropy ๐ฐ. This is achieved by taking the current time in microseconds for feeding the libc pseudo random number generator with an initial value. openssl is then fed with output fromrandom()calls.
NOTE: This mechanism is not sufficient for generation of secure keys! ๐
compressโ enable or disable the use of compression for a connection ๐๏ธ. Setting this to"none"disables compression, setting it to"auto"lets OpenSSL choose the best available algorithm supported by both parties. The default is to not touch any compression-related settings. NOTE: Requires OpenSSL0.9.8or higher and disabling compression with OpenSSL0.9.8affects all new connections in the process ๐.commonname=<string>โ specify the commonname that the peer certificate must match ๐ชช. WithOPENSSL-CONNECTaddress this overrides the given hostname or IP target address; withOPENSSL-LISTENthis turns on check of peer certificates commonname. This option has only meaning when optionverifyis not disabled and the chosen cipher provides a peer certificate.no-sni[=<bool>]โ do not use the client side Server Name Indication (SNI) feature that selects the desired server certificate ๐. Note: SNI is automatically used since socat version1.7.4.0and usescommonnameor the given host name.snihost=<string>โ set the client side Server Name Indication (SNI) host name different from the addressed server name or common name ๐ฆ. This might be useful when the server certificate has multiple host names or wildcard names because the SNI host name is passed in cleartext to the server and might be eavesdropped; with this option a mock name of the desired certificate may be transferred ๐.fipsโ enables FIPS mode if compiled in ๐. For info about the FIPS encryption implementation standard seehttp://oss-institute.org/fips-faq.html. This mode might require that the involved certificates are generated with a FIPS enabled version of openssl. Setting or clearing this option on one socat address affects all OpenSSL addresses of this process ๐ณ.
๐ RETRY option group ๐
Options that control retry of some system calls, especially connection attempts ๐.
retry=<num>โ number of retries before the connection or listen attempt is aborted. Default is0, which means just one attempt.interval=<timespec>โ time between consecutive attempts (seconds, [timespec]). Default is1second โฑ๏ธ.foreverโ performs an unlimited number of retry attempts โพ๏ธ.
๐ INTERFACE option group ๐
These options may be applied to addresses INTERFACE and TUN. These address types and options are currently only implemented on Linux operating system ๐ง.
Note regarding VLANs: On incoming packets the Linux kernel strips off the VLAN tag before passing the data to the user space program on raw sockets ๐. Special measures are required to get the VLAN information, seepacket(7)PACKET_AUXDATA, and to optionally insert the tag into the packet again, use optionretrieve-vlanwhen you need this.
retrieve-vlanโ on packets incoming on raw sockets, retrieve the VLAN information and insert it into the packets for further processing (Linux) ๐ท๏ธ.iff-upโ flips the TUN network interface status to UP. Strongly recommended, bestie, like do not skip this one.iff-broadcastโ sets the BROADCAST flag of the TUN network interface.iff-debugโ sets the DEBUG flag of the TUN network interface.iff-loopbackโ sets the LOOPBACK flag of the TUN network interface.iff-pointopointโ sets the POINTOPOINT flag of the TUN device.iff-notrailersโ sets the NOTRAILERS flag of the TUN device.iff-runningโ sets the RUNNING flag of the TUN device.iff-noarpโ sets the NOARP flag of the TUN device.iff-promiscโ sets the PROMISC flag of the TUN device.iff-allmultiโ sets the ALLMULTI flag of the TUN device.iff-masterโ sets the MASTER flag of the TUN device.iff-slaveโ sets the SLAVE flag of the TUN device.iff-multicastโ sets the MULTICAST flag of the TUN device.iff-portselโ sets the PORTSEL flag of the TUN device.iff-automediaโ sets the AUTOMEDIA flag of the TUN device.iff-dynamicโ sets the DYNAMIC flag of the TUN device.interface-mtu=<num>(if-mtu=<num>) โ sets the interface's MTU, and it does it through the netlink interface. fancy.
TUN option group ๐ฆ
okay so this little group is all about Linux TUN/TAP interface device addresses. yes, the whole vibe here is "pretend to be a network card".
tun-device=<device-file>โ tellssocatto go look somewhere else for the TUN clone device. The default is/dev/net/tun.tun-name=<if-name>โ gives the resulting network interface a specific name of your choosing, instead of the name the system just generates for you (tun0,tun1, etc.) โจtun-type=[tun|tap]โ sets the type of the TUN device; use this one if you want to make a TAP device. The Linux docs explain the difference between these two types, go read those. ๐ and real talk: when you're trying to build a tunnel between two TUN devices, their types should be the same.iff-no-piโ sets theIFF_NO_PIflag, which controls whether the device sticks extra packet information into the tunnel. and same energy as above: when you're establishing a tunnel between two TUN devices, these flags should have the same values. no cap.
POSIX-MQ option group ๐
these are the options you can apply to POSIX-MQ addresses. she's niche but she's iconic.
posixmq-priority=<unsigned int>(mq-prio) โ sets the priority of the messages (packets) written to the queue, or the minimal priority of a packet to be read from the queue.posixmq-flush(mq-flush) โ "consumes" (drops) every message currently sitting in the queue before transfers even start. a lil spring cleaning moment.posixmq-maxmsg=<long>(mq-maxmsg) โ sets themaxmsgparameter of the POSIX message queue when creating it.
Note: this option only applies when the queue does not already exist.
Note: the value is restricted by the kernel setting/proc/sys/fs/mqueue/msg_max, and the system default there is as low as10. ๐
posixmq-msgsize=<long>(mq-msgsize) โ sets themsgsizeparameter of the POSIX message queue when creating it.
Note: this option only applies when the queue does not already exist.
Note: the value is restricted by the kernel setting /proc/sys/fs/mqueue/msgsize_max.
DATA VALUES ๐
okay bestie, this section is the glossary. it explains all the different data types that address parameters and address options can take. lowkey the most useful part, fr fr.
address-rangeโ is currently only implemented for IPv4 and IPv6. see the address-optionrange.boolโ"0"or"1"; if the value is omitted,"1"is taken. default to yes energy.byteโ an unsigned int number, read withstrtoul(), lower or equal toUCHAR_MAX.command-lineโ a string specifying a program name and its arguments, separated by single spaces.dataโ this is a more general data specification,"dalan"(low level data description language). the given text string contains information about the target data type and value. generally a leading character specifies the type of the following data item. in its specific context a default data type may exist. currently only the following specifications are implemented:iโ a signed integer number, stored in host byte order. Example:i-1000(Integer number -1000)Iโ an unsigned integer number, stored in host byte order.lโ a signed long integer number, stored in host byte order.Lโ an unsigned long integer number, stored in host byte order.sโ a signed short integer number, stored in host byte order.Sโ an unsigned short integer number, stored in host byte order.bโ a signed byte (signed char).Bโ an unsigned byte (unsigned char).xโ following is an even number of hex digits, stored as a sequence of bytes, the data length is the resulting number of bytes. Example:x7f000001(IP address 127.0.0.1)"โ following is a string that is used with the common conversions\n\r\t\f\b\a\e\0; the string must be closed with". please note that the quotes and backslashes need to be escaped from shell and socat conversion. no implicit\0is appended. Example:"Hello world!\n"'โ a single char, with the usual conversions. please note that the quotes and backslashes need to be escaped from shell and socat conversion. Example:'a'
data items may be separated with white space without needing to repeat the type specifier again. efficient queen.
directoryโ a string with usual UN*X directory name semantics.facilityโ the name of a syslog facility in lower case characters.fdnumโ an unsigned int type, read withstrtoul(), specifying a UN*X file descriptor.filenameโ a string with usual UN*X filename semantics.groupโ if the first character is a decimal digit, the value is read withstrtoul()as unsigned integer specifying a group id. otherwise, it must be an existing group name.intโ a number following the rules of thestrtol()function with base"0", i.e. decimal number, octal number with leading"0", or hexadecimal number with leading"0x". the value must fit into a Cint.interfaceโ a string specifying the device name of a network interface as shown byifconfigorprocan, e.g."eth0".IP addressโ an IPv4 address in numbers-and-dots notation, an IPv6 address in hex notation enclosed in brackets, or a hostname that resolves to an IPv4 or an IPv6 address. Examples:127.0.0.1,[::1],www.dest-unreach.org,dns1IPv4 addressโ an IPv4 address in numbers-and-dots notation or a hostname that resolves to an IPv4 address. Examples:127.0.0.1,www.dest-unreach.org,dns2IPv6 addressโ an IPv6 address in hexnumbers-and-colons notation enclosed in brackets, or a hostname that resolves to an IPv6 address. Examples:[::1],[1234:5678:9abc:def0:1234:5678:9abc:def0],ip6name.domain.orglongโ a number read withstrtol(). the value must fit into a Clong.long longโ a number read withstrtoll(). the value must fit into a Clong long.off_tโ an implementation dependent signed number, usually 32 bits, read withstrtolorstrtoll.off64_tโ an implementation dependent signed number, usually 64 bits, read withstrtolorstrtoll.mode_tโ an unsigned integer, read withstrtoul(), specifying mode (permission) bits.pid_tโ a number, read withstrtol(), specifying a process id.portโ auint16_t(16 bit unsigned number) specifying a TCP or UDP port, read withstrtoul().protocolโ an unsigned 8 bit number, read withstrtoul().size_tโ an unsigned number withsize_tlimitations, read withstrtoul.socknameโ a socket address. see the address-optionbind.stringโ a sequence of characters, not containing'\0'and, depending on the position within the command line,':',',', or"!!". note that you might have to escape shell meta characters in the command line.TCP serviceโ a service name, not starting with a digit, that is resolved bygetservbyname(), or an unsigned int 16 bit number read withstrtoul().timevalโ a double float specifying seconds; the number is mapped into astruct timeval, consisting of seconds and microseconds.timespecโ a double float specifying seconds; the number is mapped into astruct timespec, consisting of seconds and nanoseconds.UDP serviceโ a service name, not starting with a digit, that is resolved bygetservbyname(), or an unsigned int 16 bit number read withstrtoul().unsigned intโ a number read withstrtoul(). the value must fit into a Cunsigned int.userโ if the first character is a decimal digit, the value is read withstrtoul()as unsigned integer specifying a user id. otherwise, it must be an existing user name.VSOCK cidโ auint32_t(32 bit unsigned number) specifying a VSOCK Context Identifier (CID), read withstrtoul(). there are several special addresses:VMADDR_CID_ANY(-1U) means any address for binding;VMADDR_CID_HOST(2) is the well-known address of the host.VSOCK portโ auint32_t(32 bit unsigned number) specifying a VSOCK port, read withstrtoul().
EXAMPLES ๐
the moment you've been waiting for. real commands, real vibes.
socat - TCP4:www.domain.org:80
socat - TCP4:www.domain.org:80
transfers data between STDIO (-) and a TCP4 connection to port 80 of host www.domain.org. this example results in an interactive connection similar to telnet or netcat. the stdin terminal parameters are not changed, so you may close the relay with ^D or abort it with ^C. no notes, iconic.
socat -d -d \/READLINE,history=$HOME/.http_history \/TCP4:www.domain.org:www,crnl
socat -d -d \
READLINE,history=$HOME/.http_history \
TCP4:www.domain.org:www,crnl
this is similar to the previous example, but you can edit the current line in a bash like manner (READLINE) and use the history file .http_history; socat prints messages about progress (-d -d). the port is specified by service name (www), and correct network line termination characters (crnl) instead of NL are used. ๐
socat \/TCP4-LISTEN:www \/TCP4:www.domain.org:www
socat \
TCP4-LISTEN:www \
TCP4:www.domain.org:www
installs a simple TCP port forwarder. with TCP4-LISTEN it listens on local port "www" until a connection comes in, accepts it, then connects to the remote host (TCP4) and starts data transfer. it will not accept a second connection. one and done, bestie.
socat -d -d -lmlocal2 \/TCP4-LISTEN:80,bind=myaddr1,reuseaddr,fork,su=nobody,range=10.0.0.0/8 \/TCP4:www.domain.org:80,bind=myaddr2
socat -d -d -lmlocal2 \
TCP4-LISTEN:80,bind=myaddr1,reuseaddr,fork,su=nobody,range=10.0.0.0/8 \
TCP4:www.domain.org:80,bind=myaddr2
...it handles, like, an almost arbitrary number of parallel or consecutive connections by fork'ing a fresh new process after each accept() ๐ซถ. It's giving responsible big-sibling energy too: it adds a lil security by su'ing to user nobody after forking. Also it only permits connections from the private 10 network (range). And thanks to reuseaddr, it can restart immediately after the master process's termination, even if some child sockets aren't completely shut down yet. With -lmlocal2, socat logs to stderr until it successfully reaches the accept loop. After that? Further logging is directed to syslog with facility local2. so organized of it honestly โจ
socat \
TCP4-LISTEN:5555,fork,tcpwrap=script \
EXEC:/bin/myscript,chroot=/home/sandbox,su-d=sandbox,pty,stderr
a simple server that accepts connections (TCP4-LISTEN) and fork's a new child process for every single connection โ every child acts as a single relay. The client has to match the rules for daemon process name "script" in /etc/hosts.allow and /etc/hosts.deny, otherwise it gets refused access (see "man 5 hosts_access") ๐
โ๏ธ. For EXEC'uting the program, the child process chroot's to /home/sandbox, su's to user sandbox, and then starts the program /home/sandbox/bin/myscript. Socat and myscript communicate via a pseudo tty (pty); myscript's stderr is redirected to stdout, so its error messages get transferred via socat to the connected client. error messages taking the scenic route, we love to see it ๐
socat \
EXEC:"mail.sh target@domain.com",fdin=3,fdout=4 \
TCP4:mail.relay.org:25,crnl,bind=alias1.server.org,mss=512
mail.sh is a shell script, distributed with socat, that implements a simple SMTP client. It is programmed to "speak" SMTP on its FDs 3 (in) and 4 (out). The fdin and fdout options tell socat to use these FDs for communication with the program. Because mail.sh inherits stdin and stdout while socat does not use them, the script can read a mail body from stdin. Socat makes alias1 your local source address (bind), cares for correct network line termination (crnl) and sends at most 512 data bytes per packet (mss). multi-tasking icon behavior fr ๐
socat \
-,escape=0x0f \
/dev/ttyS0,rawer,crnl
opens an interactive connection via the serial line, e.g. for talking with a modem ๐. rawer sets the console's and ttyS0's terminal parameters to practicable values, crnl converts to correct newline characters. escape allows terminating the socat process with character control-O. Consider using READLINE instead of the first address. ๐
socat \
UNIX-LISTEN:/tmp/.X11-unix/X1,fork \
SOCKS4:host.victim.org:127.0.0.1:6000,socksuser=nobody,sourceport=20
with UNIX-LISTEN, socat opens a listening UNIX domain socket /tmp/.X11-unix/X1. This path corresponds to local XWindow display :1 on your machine, so XWindow client connections to DISPLAY=:1 are accepted. Socat then speaks with the SOCKS4 server host.victim.org that might permit sourceport 20 based connections due to an FTP related weakness in its static IP filters ๐ญ. Socat pretends to be invoked by socksuser nobody, and requests to be connected to loopback port 6000 (only weak sockd configurations will allow this). So we get a connection to the victims XWindow server and, if it does not require MIT cookies or Kerberos authentication, we can start work. Please note that there can only be one connection at a time, because TCP can establish only one session with a given set of addresses and ports. no cap.
socat -u \
/tmp/readdata,seek-end=0,ignoreeof \
STDIO
this is an example for unidirectional data transfer (-u) ๐ฆ. Socat transfers data from file /tmp/readdata (implicit address GOPEN), starting at its current end (seek-end=0 lets socat start reading at current end of file; use seek=0 or no seek option to first read the existing data) in a "tail -f" like mode (ignoreeof). The "file" might also be a listening UNIX domain socket (do not use a seek option then). lowkey so versatile โจ
(sleep 5; echo PASSWORD; sleep 5; echo ls; sleep 1) | \
socat - \
EXEC:'ssh -l user server',pty,setsid,ctty
EXEC'utes an ssh session to server. Uses a pty for communication between socat and ssh, makes it ssh's controlling tty (ctty), and makes this pty the owner of a new process group (setsid), so ssh accepts the password from socat ๐ฅ.
socat -u \
TCP4-LISTEN:3334,reuseaddr,fork \
OPEN:/tmp/in.log,creat,append
implements a simple network based message collector ๐ฅ. For each client connecting to port 3334, a new child process is generated (option fork). All data sent by the clients are append'ed to the file /tmp/in.log. If the file does not exist, socat creat's it. Option reuseaddr allows immediate restart of the server process. the way it just keeps collectingโฆ ๐
socat \
READLINE,noecho='[Pp]assword:' \
EXEC:'ftp ftp.server.com',pty,setsid,ctty
wraps a command line history (READLINE) around the EXEC'uted ftp client utility. This allows editing and reuse of FTP commands for relatively comfortable browsing through the ftp directory hierarchy. The password is echoed! ๐ญ pty is required to have ftp issue a prompt. Nevertheless, there may occur some confusion with the password and FTP prompts. ngl, awkward but iconic ๐
socat \
PTY,link=$HOME/dev/vmodem0,rawer,wait-slave \
EXEC:'"ssh modemserver.us.org socat - /dev/ttyS0,nonblock,rawer"'
generates a pseudo terminal device (PTY) on the client that can be reached under the symbolic link $HOME/dev/vmodem0 ๐. An application that expects a serial line or modem can be configured to use $HOME/dev/vmodem0; its traffic will be directed to a modemserver via ssh where another socat instance links it to /dev/ttyS0. socat-ception ๐
sudo socat --experimental \
TCP4-LISTEN:8000,reuseaddr,fork,netns=namespace1 \
TCP4-CONNECT:server2:8000
creates a listener in the given network namespace that accepts TCP connections on port 8000 and forwards them to server2. namespace era โญ
sudo socat --experimental \
TUN:192.168.2.1/24,up \
TUN:192.168.2.2/24,up,netns=namespace2
creates two virtual network interfaces, one in default namespace, the other one in namespace2, and forwards packets between them, acting as a virtual network connection. virtual network connection bestie!! ๐ฅ
socat \
TCP4-LISTEN:2022,reuseaddr,fork \
PROXY:proxy.local:www.domain.org:22,proxyport=3128,proxyauth=username:s3cr3t
starts a forwarder that accepts connections on port 2022, and directs them through the proxy daemon listening on port 3128 (proxyport) on host proxy.local, using the CONNECT method, where they are authenticated as "username" with "s3cr3t" (proxyauth). proxy.local should establish connections to host www.domain.org on port 22 then. gatekeeping, but literally ๐
socat - \
SSL:server:4443,cafile=./server.crt,cert=./client.pem
is an OpenSSL client that tries to establish a secure connection to an SSL server. Option cafile specifies a file that contains trust certificates: we trust the server only when it presents one of these certificates and proofs that it owns the related private key. Otherwise the connection is terminated ๐ซ. With cert a file containing the client certificate and the associated private key is specified. This is required in case the server wishes a client authentication; many Internet servers do not. The first address ('-') can be replaced by almost any other socat address. ๐ฆ
socat \
OPENSSL-LISTEN:4443,reuseaddr,pf=ip4,fork,cert=./server.pem,cafile=./client.crt \
PIPE
is an OpenSSL server that accepts TCP connections, presents the certificate from the file server.pem and forces the client to present a certificate that is verified against cafile.crt. The second address ('PIPE') can be replaced by almost any other socat address. For instructions on generating and distributing OpenSSL keys and certificates see the additional socat docu socat-openssl.txt. iykyk ๐
echo |
socat -u - \
FILE:/tmp/bigfile,create,largefile,seek=100000000000
creates a 100GB+1B sparse file; this requires a file system type that supports this (ext2, ext3, ext4, reiserfs, xfs; not minix, vfat). The operation of writing 1 byte might take long (reiserfs: some minutes; ext2: "no" time), and the resulting file can consume some disk space with just its inodes (reiserfs: 2MB; ext2: 16KB). the way 1 byte can be so dramatic ๐ญ
socat \
TCP-L:7777,reuseaddr,fork \
SYSTEM:'filan -i 0 -s >&2',nofork
listens for incoming TCP connections on port 7777. For each accepted connection, invokes a shell. This shell has its stdin and stdout directly connected to the TCP socket (nofork). The shell starts filan and lets it print the socket addresses to stderr (your terminal window). surprise, it's your terminal ๐
socat \
STDIO,cfmakeraw \
SHELL,pty,setsid,ctty,stderr
creates a shell in the current terminal that provides job control, history etc. ๐ glow up for your terminal
echo -e "\0\14\0\0\c" |
socat -u - \
FILE:/usr/bin/squid.exe,seek=0x00074420
functions as primitive binary editor: it writes the 4 bytes 000 014 000 000 to the executable /usr/bin/squid.exe at offset 0x00074420 (this was a real world patch to make the squid executable from Cygwin run under Windows, in 2004). history!! real world patch!! ๐
socat - \
TCP:www.blackhat.org:31337,readbytes=1000
connects to an unknown service and prevents being flooded. unknown service bestieโฆ be careful ๐
socat -U \
TCP:target:9999,end-close \
TCP-L:8888,reuseaddr,fork
merges data arriving from different TCP streams on port 8888 to just one stream to target:9999. The end-close option prevents the child processes forked off by the second address from terminating the shared connection to 9999 (close(2) just unlinks the inode which stays active as long as the parent process lives; shutdown(2) would actively terminate the connection). nerdy detail and we are obsessed ๐ฅ
socat \
TCP-LISTEN:10021,reuseaddr,socktype=6,protocol=33,fork PIPE
Okay so this one is a simple DCCP echo server ๐
. DCCP is now directly provisioned in socat, but this example shows how to use socat's TCP procedures and change the socket type to SOCK_DCCP=6 (on Linux) and the IP protocol to IPPROTO_DCCP=33. It's giving clever workaround energy โจ.
socat - \
TCP:<server>:10021,reuseaddr,socktype=6,protocol=33,fork
is a simple DCCP client. DCCP is now directly provisioned in socat, but this example shows how to use socat's TCP procedures, just changing the socket type to SOCK_DCCP=6 (on Linux) and the IP protocol to IPPROTO_DCCP=33.
socat - \
UDP4-DATAGRAM:192.168.1.0:123,sp=123,broadcast,range=192.168.1.0/24
sends a broadcast to the network 192.168.1.0/24 and receives the replies of the timeservers there. Ignores NTP packets from hosts outside this network.
socat - \
SOCKET-DATAGRAM:2:2:17:x007bxc0a80100x0000000000000000,bind=x007bx00000000x0000000000000000,setsockopt-int=1:6:1,range=x0000xc0a80100x0000000000000000:x0000xffffff00x0000000000000000
is semantically equivalent to the previous example, but all parameters are specified in generic form. The value 6 of setsockopt-int is the Linux value for SO_BROADCAST.
socat - \
IP4-DATAGRAM:255.255.255.255:44,broadcast,range=10.0.0.0/8
sends a broadcast to the local network(s) using protocol 44. Accepts replies from the private address range only.
socat - \
UDP4-DATAGRAM:224.255.0.1:6666,bind=:6666,ip-add-membership=224.255.0.1:eth0
transfers data from stdin to the specified multicast address using UDP. Both local and remote ports are 6666. Tells the interface eth0 to also accept multicast packets of the given group. Multiple hosts on the local network can run this command, so all data sent by any of the hosts will be received by all the other ones. Note that there are many possible reasons for failure, including IP-filters, routing issues, wrong interface selection by the operating system, bridges, or a badly configured switch. It's giving "so many ways to break" vibes ๐ญ.
socat \
UDP:host2:4443 \
TUN:192.168.255.1/24,up
establishes one side of a virtual (but not private!) network with host2 where a similar process might run, with UDP-L and tun address 192.168.255.2. They can reach each other using the addresses 192.168.255.1 and 192.168.255.2. Note that streaming eg.via TCP or SSL does not guarantee to retain packet boundaries and might thus cause packet loss.
socat - \
VSOCK-CONNECT:2:1234
establishes a VSOCK connection with the host (host is always reachable with the well-know CID=2) on 1234 port.
socat - \
VSOCK-LISTEN:1234
listens for a VSOCK connection on 1234 port.
socat - \
VSOCK-CONNECT:31:4321,bind:5555
establishes a VSOCK connection with the guest that have CID=31 on 1234 port, binding the local socket to the 5555 port.
socat \
VSOCK-LISTEN:3333,reuseaddr,fork \
VSOCK-CONNECT:42,3333
starts a forwarder that accepts VSOCK connections on port 3333, and directs them to the guest with CID=42 on the same port.
socat \
VSOCK-LISTEN:22,reuseaddr,fork \
TCP:localhost:22
forwards VSOCK connections from 22 port to the local SSH server. Running this in a VM allows you to connect via SSH from the host using VSOCK, as in the example below.
socat \
TCP4-LISTEN:22222,reuseaddr,fork \
VSOCK-CONNECT:33:22
forwards TCP connections from 22222 port to the guest with CID=33 listening on VSOCK port 22. Running this in the host, allows you to connect via SSH running "ssh -p 22222 user@localhost", if the guest runs the example above.
socat \
PTY,link=/var/run/ppp,rawer \
INTERFACE:hdlc0
circumvents the problem that pppd requires a serial device and thus might not be able to work on a synchronous line that is represented by a network device. socat creates a PTY to make pppd happy, binds to the network interface hdlc0, and can transfer data between both devices. Use pppd on device /var/run/ppp then.
socat -u \
STDIO \
POSIXMQ-SEND:/queue1,unlink-early,mq-prio=10
Writes packets read from stdio (i.e., lines of input when run interactively) into POSIX message queue, with priority 10.
socat -u \
POSIXMQ-RECV:/queue1,fork,max-children=3 \
SYSTEM:"worker.sh"
Receives messages (packets) from POSIX message queue and, for each message, forks a sub process that reads and processes the message. At most 3 sub processes are allowed at the same time.
socat -T 1 -d -d \
TCP-L:10081,reuseaddr,fork,crlf \
SYSTEM:"echo -e \"\\\"HTTP/1.0 200 OK\\\nDocumentType: text/plain\\\n\\\ndate: \$\(date\)\\\nserver:\$SOCAT_SOCKADDR:\$SOCAT_SOCKPORT\\\nclient: \$SOCAT_PEERADDR:\$SOCAT_PEERPORT\\\n\\\"\"; cat; echo -e \"\\\"\\\n\\\"\""
creates a very primitive HTTP echo server: each HTTP client that connects gets a valid HTTP reply that contains information about the client address and port as it is seen by the server host, the host address (which might vary on multihomed servers), and the original client request.
socat -d -d \
UDP4-RECVFROM:9999,so-broadcast,so-timestamp,ip-pktinfo,ip-recverr,ip-recvopts,ip-recvtos,ip-recvttl!!- \
SYSTEM:'export; sleep 1' |
grep SOCAT
waits for an incoming UDP packet on port 9999 and prints the environment variables provided by socat. On BSD based systems you have to replace ip-pktinfo with ip-recvdstaddr,ip-recvif. Especially of interest is SOCAT_IP_DSTADDR: it contains the target address of the packet which may be a unicast, multicast, or broadcast address.
echo -e "M-SEARCH * HTTP/1.1\nHOST: 239.255.255.250:1900\nMAN: \"ssdp:discover\"\nMX: 4\nST: \"ssdp:all\"\n" |
socat - \
UDP-DATAGRAM:239.255.255.250:1900,crlf
sends an SSDP (Simple Service Discovery Protocol) query to the local network and collects and outputs the answers received.
systemd-socket-activate -l 1077 --inetd socat ACCEPT:0,fork PIPE
systemd-socket-activate is a program for testing systemd socket activation of daemons. With --inetd it waits for a connection on the specified port. It does not accept the connection but passes the listening file descriptor as FDs 0 and 1. Socat accepts the waiting connection and starts data transfer.
sudo socat -u TEXT:"0 $((2**31-1))" /proc/sys/net/ipv4/ping_group_range
Writes text into a /proc/sys/ file using sudo using socat TEXT address instead of piping it to a tee under sudo.
โจ DIAGNOSTICS โจ
Socat uses a logging mechanism that allows filtering messages by severity. The severities provided are more or less compatible to the appropriate syslog priority. With one or up to four occurrences of the -d command line option, the lowest priority of messages that are issued can be selected. Each message contains a single uppercase character specifying the messages severity (one of F, E, W, N, I, or D).
FATALโ Conditions that require unconditional and immediate program termination.ERRORโ Conditions that prevent proper program processing. Usually the program is terminated (see option-s).WARNINGโ Something did not function correctly or is in a state where correct further processing cannot be guaranteed, but might be possible.NOTICEโ Interesting actions of the program, e.g. for supervising socat in some kind of server mode.INFOโ Description of what the program does, and maybe why it happens. Allows monitoring the lifecycles of file descriptors.DEBUGโ Description of how the program works, all system or library calls and their results.
Log messages can be written to stderr, to a file, or to syslog.
On exit, socat gives status 0 if it terminated due to EOF or inactivity timeout, with a positive value on error, and with a negative value on fatal error.
๐ FILES ๐
/usr/bin/socat/usr/bin/filan/usr/bin/procan
๐จ SIGNALS ๐จ
SIGUSR1โ Causes logging of current transfer statistics. See also option--statistics
๐ ENVIRONMENT VARIABLES ๐
Okay so this is where socat and your shell hold hands ๐ค โ input variables carry info from the environment into socat, and output variables get set by socat so your executed scripts and programs can read them.
Little detail that matters: in the output variables that start with "SOCAT", that prefix actually gets replaced by the upper case name of the executable, or by whatever you passed to option -lp.
SOCAT_DEFAULT_LISTEN_IP(input) โ values4or6. Picks the IP version used forlisten,recv, andrecvfromaddresses when nopf(protocol-family) option is given. It gets overridden by the socat options-4or-6. So those flags win, periodt.SOCAT_PREFERRED_RESOLVE_IP(input) โ values0,4, or6. Sets the IP version used when resolving target host names, in the case where the version isn't specified by address type, by optionpf(protocol-family), or by address format. If name resolution doesn't return a matching entry, the first result (with a differing IP version) is taken. With value0, socat always selects the first record and its IP version. no cap.SOCAT_MAIN_WAIT(input) โ the time (in seconds) to sleep the main process at the beginning ofmain(). It's a debugging thing ๐.SOCAT_TRANSFER_WAIT(input) โ the time (in seconds) to sleep the process after opening addresses but before entering the transfer loop. Also for debugging, bestie.SOCAT_FORK_WAIT(input) โ the time (in seconds) to sleep the parent and child processes after a successfulfork(). Debugging again ๐ .SOCAT_VERSION(output) โ socat sets this to its version string, like"1.7.0.0"for released versions, or e.g."1.6.0.1+envvar"for temporary versions. Perfect for scripts that socat invokes โจ.SOCAT_PID(output) โ socat sets this to its process id. With theforkaddress option,SOCAT_PIDgets the child process's id. Forking forexec,system, andSHELLdoes not changeSOCAT_PID.SOCAT_PPID(output) โ socat sets this to its process id. In case of fork,SOCAT_PPIDkeeps the pid of the master process.SOCAT_PEERADDR(output) โ with passive socket addresses (that's allLISTENandRECVFROMaddresses), this gets set to a string describing the peer's socket address. Port information is not included.SOCAT_PEERPORT(output) โ with appropriate passive socket addresses (TCP,UDP, andSCTPโLISTENandRECVFROM), this is set to a string containing the number of the peer port.SOCAT_SOCKADDR(output) โ with allLISTENaddresses, this is set to a string describing the local socket address. Port information is not included example ๐ and yes, the manpage literally ends that sentence with the word "example" and we are keeping it, iykyk ๐ญSOCAT_SOCKPORT(output) โ withTCP-LISTEN,UDP-LISTEN, andSCTP-LISTENaddresses, this is set to the local port.SOCAT_TIMESTAMP(output) โ with allRECVFROMaddresses where the address optionso-timestampis applied, socat sets this variable to the resulting timestamp ๐ฐ๏ธ.SOCAT_IP_OPTIONS(output) โ with all IPv4 basedRECVFROMaddresses where the address optionip-recvoptsis applied, socat fills this with the IP options of the received packet.SOCAT_IP_DSTADDR(output) โ with all IPv4 basedRECVFROMaddresses where the address optionip-recvdstaddr(BSD) orip-pktinfo(other platforms) is applied, socat sets this to the destination address of the received packet. Super useful for identifying broadcast and multicast addressed packets ๐ฌ.SOCAT_IP_IF(output) โ with all IPv4 basedRECVFROMaddresses where the address optionip-recvif(BSD) orip-pktinfo(other platforms) is applied, socat sets this to the name of the interface where the packet was received.SOCAT_IP_LOCADDR(output) โ with all IPv4 basedRECVFROMaddresses where the address optionip-pktinfois applied, socat sets this to the address of the interface where the packet was received.SOCAT_IP_TOS(output) โ with all IPv4 basedRECVFROMaddresses where the address optionip-recvtosis applied, socat sets this to the TOS (type of service) of the received packet.SOCAT_IP_TTL(output) โ with all IPv4 basedRECVFROMaddresses where the address optionip-recvttlis applied, socat sets this to the TTL (time to live) of the received packet.SOCAT_IPV6_HOPLIMIT(output) โ with all IPv6 basedRECVFROMaddresses where the address optionipv6-recvhoplimitis applied, socat sets this to the hoplimit value of the received packet.SOCAT_IPV6_DSTADDR(output) โ with all IPv6 basedRECVFROMaddresses where the address optionipv6-recvpktinfois applied, socat sets this to the destination address of the received packet.SOCAT_IPV6_TCLASS(output) โ with all IPv6 basedRECVFROMaddresses where the address optionipv6-recvtclassis applied, socat sets this to the transfer class of the received packet.SOCAT_OPENSSL_X509_ISSUER(output) โ issuer field from peer certificate.SOCAT_OPENSSL_X509_SUBJECT(output) โ subject field from peer certificate.SOCAT_OPENSSL_X509_COMMONNAME(output) โ commonName entries from the peer certificate's subject. Multiple values are separated by" // ".SOCAT_OPENSSL_X509_*(output) โ all other entries from the peer certificate's subject.SOCAT_OPENSSL_X509V3_DNS(output) โ DNS entries from the peer certificate's extensions โ the subjectAltName field. Multiple values are separated by" // ".HOSTNAME(input) โ used to determine the hostname for logging (see-lh).LOGNAME(input) โ used as the name for the socks client user name when nosocksuseris given. With the optionssuandsu-d,LOGNAMEis set to the given user name.USER(input) โ used as the name for the socks client user name when nosocksuseris given andLOGNAMEis empty. With the optionssuandsu-d,USERis set to the given user name.SHELL(output) โ with the optionssuandsu-d,SHELLis set to the login shell of the given user.PATH(output) โ can be set with the optionpathforexec,system, andSHELLaddresses.HOME(output) โ with the optionssuandsu-d,HOMEis set to the home directory of the given user ๐ .
๐ CREDITS ๐
The work of these groups and organizations was genuinely invaluable for this project, and we're giving them their flowers ๐ธ:
- The FSF (GNU, http://www.fsf.org/) project with their free and portable development software, plus lots of other useful tools and libraries.
- The Linux developers community (http://www.linux.org/) for providing a free, open source operating system. iconic behavior.
- The Open Group (http://www.unix-systems.org/) for making their standard specifications available on the Internet for free. king shit ๐
โญ VERSION โญ
This man page describes version 1.8.1 of socat. ๐
๐ BUGS ๐
Not me listing the Ls, but here we go, we keep it 100:
- Addresses cannot be nested, so a single socat process cannot, e.g., drive ssl over socks. Tragic but true ๐ญ
- Address option
ftruncatewithout a value uses default1instead of0. - Verbose modes (
-xand/or-v) display line termination characters inconsistently when the address optionscrorcrnlare used: they show the data after conversion, in either direction. - The data transfer blocksize setting (
-b) is ignored with the addressreadline. - Send bug reports to
<socat@dest-unreach.org>๐๐ฎ
๐ SEE ALSO ๐
nc(1), rinetd(8), openssl(1), stunnel(8), rlwrap(1), setsid(1)
Socat home page: http://www.dest-unreach.org/socat/ ๐
๐ AUTHOR ๐
Gerhard Rieger <rieger@dest-unreach.org> and contributors ๐ซถ
and that's the whole page, bestie!! ๐ This one's the socat(1) man page from the socat source, version 1.8.1 of socat, dated in the original footer โ go read the source, follow the links, and send Gerhard and the contributors some love, they ate ๐โจ๐ฆ
๐ฆ where this page comes from
- alpine 3.22: socat-doc 1.8.1.3-r0 ยท GPL-2.0-only WITH OpenSSL-Exception
- alpine 3.23: socat-doc 1.8.1.3-r0 ยท GPL-2.0-only WITH OpenSSL-Exception
- alpine 3.24: socat-doc 1.8.1.3-r0 ยท GPL-2.0-only WITH OpenSSL-Exception
- arch rolling: socat 1.8.1.3-1 ยท GPL-2.0-only
- fedora 43: socat 1.8.1.1-2.fc43
- fedora 43: socat 1.8.1.3-1.fc43 ยท GPL-2.0-only
- fedora 44: socat 1.8.1.1-1.fc44
- fedora 44: socat 1.8.1.3-1.fc44 ยท GPL-2.0-only
- nixos 26.05: socat 1.8.1.3
- nixpkgs unstable: socat 1.8.1.3
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms