.TH gen_tcp 3erl "kernel 2.15.1" "Ericsson AB" "Erlang Module Definition" .SH NAME gen_tcp \- Interface to TCP/IP sockets .SH DESCRIPTION .LP The \fIgen_tcp\fR\& module provides functions for communicating with sockets using the TCP/IP protocol\&. .LP The following code fragment provides a simple example of a client connecting to a server at port 5678, transferring a binary and closing the connection: .LP .nf client() -> SomeHostInNet = "localhost", % to make it runnable on one machine {ok, Sock} = gen_tcp:connect(SomeHostInNet, 5678, [binary, {packet, 0}]), ok = gen_tcp:send(Sock, "Some Data"), ok = gen_tcp:close(Sock). .fi .LP At the other end a server is listening on port 5678, accepts the connection and receives the binary: .LP .nf server() -> {ok, LSock} = gen_tcp:listen(5678, [binary, {packet, 0}, {active, false}]), {ok, Sock} = gen_tcp:accept(LSock), {ok, Bin} = do_recv(Sock, []), ok = gen_tcp:close(Sock), Bin. do_recv(Sock, Bs) -> case gen_tcp:recv(Sock, 0) of {ok, B} -> do_recv(Sock, [Bs, B]); {error, closed} -> {ok, list_to_binary(Bs)} end. .fi .LP For more examples, see the \fBexamples\fR\& section\&. .SH DATA TYPES .nf \fBoption()\fR\& = {active, true | false | once} .br | {bit8, clear | set | on | off} .br | {buffer, integer() >= 0} .br | {delay_send, boolean()} .br | {deliver, port | term} .br | {dontroute, boolean()} .br | {exit_on_close, boolean()} .br | {header, integer() >= 0} .br | {high_watermark, integer() >= 0} .br | {keepalive, boolean()} .br | {linger, {boolean(), integer() >= 0}} .br | {low_watermark, integer() >= 0} .br | {mode, list | binary} .br | list .br | binary .br | {nodelay, boolean()} .br | {packet, .br 0 | .br 1 | .br 2 | .br 4 | .br raw | .br sunrm | .br asn1 | .br cdr | .br fcgi | .br line | .br tpkt | .br http | .br httph | .br http_bin | .br httph_bin} .br | {packet_size, integer() >= 0} .br | {priority, integer() >= 0} .br | {raw, .br Protocol :: integer() >= 0, .br OptionNum :: integer() >= 0, .br ValueBin :: binary()} .br | {recbuf, integer() >= 0} .br | {reuseaddr, boolean()} .br | {send_timeout, integer() >= 0 | infinity} .br | {send_timeout_close, boolean()} .br | {sndbuf, integer() >= 0} .br | {tos, integer() >= 0} .br .fi .nf \fBoption_name()\fR\& = active .br | bit8 .br | buffer .br | delay_send .br | deliver .br | dontroute .br | exit_on_close .br | header .br | high_watermark .br | keepalive .br | linger .br | low_watermark .br | mode .br | nodelay .br | packet .br | packet_size .br | priority .br | {raw, .br Protocol :: integer() >= 0, .br OptionNum :: integer() >= 0, .br ValueSpec :: (ValueSize :: integer() >= 0) .br | (ValueBin :: binary())} .br | recbuf .br | reuseaddr .br | send_timeout .br | send_timeout_close .br | sndbuf .br | tos .br .fi .nf \fBconnect_option()\fR\& = {ip, \fBinet:ip_address()\fR\&} .br | {fd, Fd :: integer() >= 0} .br | {ifaddr, \fBinet:ip_address()\fR\&} .br | \fBinet:address_family()\fR\& .br | {port, \fBinet:port_number()\fR\&} .br | {tcp_module, module()} .br | \fBoption()\fR\& .br .fi .nf \fBlisten_option()\fR\& = {ip, \fBinet:ip_address()\fR\&} .br | {fd, Fd :: integer() >= 0} .br | {ifaddr, \fBinet:ip_address()\fR\&} .br | \fBinet:address_family()\fR\& .br | {port, \fBinet:port_number()\fR\&} .br | {backlog, B :: integer() >= 0} .br | {tcp_module, module()} .br | \fBoption()\fR\& .br .fi .nf .B \fBsocket()\fR\& .br .fi .RS .LP As returned by accept/1,2 and connect/3,4\&. .RE .SH EXPORTS .LP .nf .B connect(Address, Port, Options) -> {ok, Socket} | {error, Reason} .br .fi .br .nf .B connect(Address, Port, Options, Timeout) -> .B {ok, Socket} | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Address = \fBinet:ip_address()\fR\& | \fBinet:hostname()\fR\& .br Port = \fBinet:port_number()\fR\& .br Options = [\fBconnect_option()\fR\&] .br Timeout = timeout() .br Socket = \fBsocket()\fR\& .br Reason = \fBinet:posix()\fR\& .br .RE .RE .RS .LP Connects to a server on TCP port \fIPort\fR\& on the host with IP address \fIAddress\fR\&\&. The \fIAddress\fR\& argument can be either a hostname, or an IP address\&. .LP The available options are: .RS 2 .TP 2 .B \fIlist\fR\&: Received \fIPacket\fR\& is delivered as a list\&. .TP 2 .B \fIbinary\fR\&: Received \fIPacket\fR\& is delivered as a binary\&. .TP 2 .B \fI{ip, ip_address()}\fR\&: If the host has several network interfaces, this option specifies which one to use\&. .TP 2 .B \fI{port, Port}\fR\&: Specify which local port number to use\&. .TP 2 .B \fI{fd, integer() >= 0}\fR\&: If a socket has somehow been connected without using \fIgen_tcp\fR\&, use this option to pass the file descriptor for it\&. .TP 2 .B \fIinet6\fR\&: Set up the socket for IPv6\&. .TP 2 .B \fIinet\fR\&: Set up the socket for IPv4\&. .TP 2 .B \fIOpt\fR\&: See \fBinet:setopts/2\fR\&\&. .RE .LP Packets can be sent to the returned socket \fISocket\fR\& using \fIsend/2\fR\&\&. Packets sent from the peer are delivered as messages: .LP .nf {tcp, Socket, Data} .fi .LP If the socket is closed, the following message is delivered: .LP .nf {tcp_closed, Socket} .fi .LP If an error occurs on the socket, the following message is delivered: .LP .nf {tcp_error, Socket, Reason} .fi .LP unless \fI{active, false}\fR\& is specified in the option list for the socket, in which case packets are retrieved by calling \fIrecv/2\fR\&\&. .LP The optional \fITimeout\fR\& parameter specifies a timeout in milliseconds\&. The default value is \fIinfinity\fR\&\&. .LP .RS -4 .B Note: .RE The default values for options given to \fIconnect\fR\& can be affected by the Kernel configuration parameter \fIinet_default_connect_options\fR\&\&. See \fBinet(3erl)\fR\& for details\&. .RE .LP .nf .B listen(Port, Options) -> {ok, ListenSocket} | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Port = \fBinet:port_number()\fR\& .br Options = [\fBlisten_option()\fR\&] .br ListenSocket = \fBsocket()\fR\& .br Reason = system_limit | \fBinet:posix()\fR\& .br .RE .RE .RS .LP Sets up a socket to listen on the port \fIPort\fR\& on the local host\&. .LP If \fIPort == 0\fR\&, the underlying OS assigns an available port number, use \fIinet:port/1\fR\& to retrieve it\&. .LP The available options are: .RS 2 .TP 2 .B \fIlist\fR\&: Received \fIPacket\fR\& is delivered as a list\&. .TP 2 .B \fIbinary\fR\&: Received \fIPacket\fR\& is delivered as a binary\&. .TP 2 .B \fI{backlog, B}\fR\&: \fIB\fR\& is an integer >= 0\&. The backlog value defaults to 5\&. The backlog value defines the maximum length that the queue of pending connections may grow to\&. .TP 2 .B \fI{ip, ip_address()}\fR\&: If the host has several network interfaces, this option specifies which one to listen on\&. .TP 2 .B \fI{port, Port}\fR\&: Specify which local port number to use\&. .TP 2 .B \fI{fd, Fd}\fR\&: If a socket has somehow been connected without using \fIgen_tcp\fR\&, use this option to pass the file descriptor for it\&. .TP 2 .B \fIinet6\fR\&: Set up the socket for IPv6\&. .TP 2 .B \fIinet\fR\&: Set up the socket for IPv4\&. .TP 2 .B \fIOpt\fR\&: See \fBinet:setopts/2\fR\&\&. .RE .LP The returned socket \fIListenSocket\fR\& can only be used in calls to \fIaccept/1,2\fR\&\&. .LP .RS -4 .B Note: .RE The default values for options given to \fIlisten\fR\& can be affected by the Kernel configuration parameter \fIinet_default_listen_options\fR\&\&. See \fBinet(3erl)\fR\& for details\&. .RE .LP .nf .B accept(ListenSocket) -> {ok, Socket} | {error, Reason} .br .fi .br .nf .B accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 ListenSocket = \fBsocket()\fR\& .br .RS 2 Returned by \fIlisten/2\fR\&\&. .RE Timeout = timeout() .br Socket = \fBsocket()\fR\& .br Reason = closed | timeout | system_limit | \fBinet:posix()\fR\& .br .RE .RE .RS .LP Accepts an incoming connection request on a listen socket\&. \fISocket\fR\& must be a socket returned from \fIlisten/2\fR\&\&. \fITimeout\fR\& specifies a timeout value in ms, defaults to \fIinfinity\fR\&\&. .LP Returns \fI{ok, Socket}\fR\& if a connection is established, or \fI{error, closed}\fR\& if \fIListenSocket\fR\& is closed, or \fI{error, timeout}\fR\& if no connection is established within the specified time, or \fI{error, system_limit}\fR\& if all available ports in the Erlang emulator are in use\&. May also return a POSIX error value if something else goes wrong, see inet(3erl) for possible error values\&. .LP Packets can be sent to the returned socket \fISocket\fR\& using \fIsend/2\fR\&\&. Packets sent from the peer are delivered as messages: .LP .nf {tcp, Socket, Data} .fi .LP unless \fI{active, false}\fR\& was specified in the option list for the listen socket, in which case packets are retrieved by calling \fIrecv/2\fR\&\&. .LP .RS -4 .B Note: .RE It is worth noting that the \fIaccept\fR\& call does \fInot\fR\& have to be issued from the socket owner process\&. Using version 5\&.5\&.3 and higher of the emulator, multiple simultaneous accept calls can be issued from different processes, which allows for a pool of acceptor processes handling incoming connections\&. .RE .LP .nf .B send(Socket, Packet) -> ok | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Socket = \fBsocket()\fR\& .br Packet = iodata() .br Reason = \fBinet:posix()\fR\& .br .RE .RE .RS .LP Sends a packet on a socket\&. .LP There is no \fIsend\fR\& call with timeout option, you use the \fIsend_timeout\fR\& socket option if timeouts are desired\&. See the \fBexamples\fR\& section\&. .RE .LP .nf .B recv(Socket, Length) -> {ok, Packet} | {error, Reason} .br .fi .br .nf .B recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Socket = \fBsocket()\fR\& .br Length = integer() >= 0 .br Timeout = timeout() .br Packet = string() | binary() | HttpPacket .br Reason = closed | \fBinet:posix()\fR\& .br HttpPacket = term() .br .RS 2 See the description of \fIHttpPacket\fR\& in \fB erlang:decode_packet/3\fR\&\&. .RE .RE .RE .RS .LP This function receives a packet from a socket in passive mode\&. A closed socket is indicated by a return value \fI{error, closed}\fR\&\&. .LP The \fILength\fR\& argument is only meaningful when the socket is in \fIraw\fR\& mode and denotes the number of bytes to read\&. If \fILength\fR\& = 0, all available bytes are returned\&. If \fILength\fR\& > 0, exactly \fILength\fR\& bytes are returned, or an error; possibly discarding less than \fILength\fR\& bytes of data when the socket gets closed from the other side\&. .LP The optional \fITimeout\fR\& parameter specifies a timeout in milliseconds\&. The default value is \fIinfinity\fR\&\&. .RE .LP .nf .B controlling_process(Socket, Pid) -> ok | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Socket = \fBsocket()\fR\& .br Pid = pid() .br Reason = closed | not_owner | \fBinet:posix()\fR\& .br .RE .RE .RS .LP Assigns a new controlling process \fIPid\fR\& to \fISocket\fR\&\&. The controlling process is the process which receives messages from the socket\&. If called by any other process than the current controlling process, \fI{error, eperm}\fR\& is returned\&. .RE .LP .nf .B close(Socket) -> ok .br .fi .br .RS .LP Types: .RS 3 Socket = \fBsocket()\fR\& .br .RE .RE .RS .LP Closes a TCP socket\&. .RE .LP .nf .B shutdown(Socket, How) -> ok | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Socket = \fBsocket()\fR\& .br How = read | write | read_write .br Reason = \fBinet:posix()\fR\& .br .RE .RE .RS .LP Immediately close a socket in one or two directions\&. .LP \fIHow == write\fR\& means closing the socket for writing, reading from it is still possible\&. .LP To be able to handle that the peer has done a shutdown on the write side, the \fI{exit_on_close, false}\fR\& option is useful\&. .RE .SH "EXAMPLES" .LP The following example illustrates usage of the {active,once} option and multiple accepts by implementing a server as a number of worker processes doing accept on one single listen socket\&. The start/2 function takes the number of worker processes as well as a port number to listen for incoming connections on\&. If \fILPort\fR\& is specified as \fI0\fR\&, an ephemeral portnumber is used, why the start function returns the actual portnumber allocated: .LP .nf start(Num,LPort) -> case gen_tcp:listen(LPort,[{active, false},{packet,2}]) of {ok, ListenSock} -> start_servers(Num,ListenSock), {ok, Port} = inet:port(ListenSock), Port; {error,Reason} -> {error,Reason} end. start_servers(0,_) -> ok; start_servers(Num,LS) -> spawn(?MODULE,server,[LS]), start_servers(Num-1,LS). server(LS) -> case gen_tcp:accept(LS) of {ok,S} -> loop(S), server(LS); Other -> io:format("accept returned ~w - goodbye!~n",[Other]), ok end. loop(S) -> inet:setopts(S,[{active,once}]), receive {tcp,S,Data} -> Answer = process(Data), % Not implemented in this example gen_tcp:send(S,Answer), loop(S); {tcp_closed,S} -> io:format("Socket ~w closed [~w]~n",[S,self()]), ok end. .fi .LP A simple client could look like this: .LP .nf client(PortNo,Message) -> {ok,Sock} = gen_tcp:connect("localhost",PortNo,[{active,false}, {packet,2}]), gen_tcp:send(Sock,Message), A = gen_tcp:recv(Sock,0), gen_tcp:close(Sock), A. .fi .LP The fact that the \fIsend\fR\& call does not accept a timeout option, is because timeouts on send is handled through the socket option \fIsend_timeout\fR\&\&. The behavior of a send operation with no receiver is in a very high degree defined by the underlying TCP stack, as well as the network infrastructure\&. If one wants to write code that handles a hanging receiver that might eventually cause the sender to hang on a \fIsend\fR\& call, one writes code like the following\&. .LP Consider a process that receives data from a client process that is to be forwarded to a server on the network\&. The process has connected to the server via TCP/IP and does not get any acknowledge for each message it sends, but has to rely on the send timeout option to detect that the other end is unresponsive\&. We could use the \fIsend_timeout\fR\& option when connecting: .LP .nf ... {ok,Sock} = gen_tcp:connect(HostAddress, Port, [{active,false}, {send_timeout, 5000}, {packet,2}]), loop(Sock), % See below ... .fi .LP In the loop where requests are handled, we can now detect send timeouts: .LP .nf loop(Sock) -> receive {Client, send_data, Binary} -> case gen_tcp:send(Sock,[Binary]) of {error, timeout} -> io:format("Send timeout, closing!~n", []), handle_send_timeout(), % Not implemented here Client ! {self(),{error_sending, timeout}}, %% Usually, it's a good idea to give up in case of a %% send timeout, as you never know how much actually %% reached the server, maybe only a packet header?! gen_tcp:close(Sock); {error, OtherSendError} -> io:format("Some other error on socket (~p), closing", [OtherSendError]), Client ! {self(),{error_sending, OtherSendError}}, gen_tcp:close(Sock); ok -> Client ! {self(), data_sent}, loop(Sock) end end. .fi .LP Usually it would suffice to detect timeouts on receive, as most protocols include some sort of acknowledgment from the server, but if the protocol is strictly one way, the \fIsend_timeout\fR\& option comes in handy!