1gen_tcp(3)                 Erlang Module Definition                 gen_tcp(3)
2
3
4

NAME

6       gen_tcp - Interface to TCP/IP sockets.
7

DESCRIPTION

9       This module provides functions for communicating with sockets using the
10       TCP/IP protocol.
11
12       The following code fragment is a simple example of a client  connecting
13       to  a  server at port 5678, transferring a binary, and closing the con‐
14       nection:
15
16       client() ->
17           SomeHostInNet = "localhost", % to make it runnable on one machine
18           {ok, Sock} = gen_tcp:connect(SomeHostInNet, 5678,
19                                        [binary, {packet, 0}]),
20           ok = gen_tcp:send(Sock, "Some Data"),
21           ok = gen_tcp:close(Sock).
22
23       At the other end, a server is listening on port 5678, accepts the  con‐
24       nection, and receives the binary:
25
26       server() ->
27           {ok, LSock} = gen_tcp:listen(5678, [binary, {packet, 0},
28                                               {active, false}]),
29           {ok, Sock} = gen_tcp:accept(LSock),
30           {ok, Bin} = do_recv(Sock, []),
31           ok = gen_tcp:close(Sock),
32           ok = gen_tcp:close(LSock),
33           Bin.
34
35       do_recv(Sock, Bs) ->
36           case gen_tcp:recv(Sock, 0) of
37               {ok, B} ->
38                   do_recv(Sock, [Bs, B]);
39               {error, closed} ->
40                   {ok, list_to_binary(Bs)}
41           end.
42
43       For more examples, see section Examples.
44

DATA TYPES

46       option() =
47           {active, true | false | once | -32768..32767} |
48           {buffer, integer() >= 0} |
49           {delay_send, boolean()} |
50           {deliver, port | term} |
51           {dontroute, boolean()} |
52           {exit_on_close, boolean()} |
53           {header, integer() >= 0} |
54           {high_msgq_watermark, integer() >= 1} |
55           {high_watermark, integer() >= 0} |
56           {keepalive, boolean()} |
57           {linger, {boolean(), integer() >= 0}} |
58           {low_msgq_watermark, integer() >= 1} |
59           {low_watermark, integer() >= 0} |
60           {mode, list | binary} |
61           list | binary |
62           {nodelay, boolean()} |
63           {packet,
64            0 | 1 | 2 | 4 | raw | sunrm | asn1 | cdr | fcgi | line |
65            tpkt | http | httph | http_bin | httph_bin} |
66           {packet_size, integer() >= 0} |
67           {priority, integer() >= 0} |
68           {raw,
69            Protocol :: integer() >= 0,
70            OptionNum :: integer() >= 0,
71            ValueBin :: binary()} |
72           {recbuf, integer() >= 0} |
73           {reuseaddr, boolean()} |
74           {send_timeout, integer() >= 0 | infinity} |
75           {send_timeout_close, boolean()} |
76           {show_econnreset, boolean()} |
77           {sndbuf, integer() >= 0} |
78           {tos, integer() >= 0} |
79           {tclass, integer() >= 0} |
80           {ttl, integer() >= 0} |
81           {recvtos, boolean()} |
82           {recvtclass, boolean()} |
83           {recvttl, boolean()} |
84           {ipv6_v6only, boolean()}
85
86       pktoptions_value() = {pktoptions, inet:ancillary_data()}
87
88              If the platform implements the IPv4 option IP_PKTOPTIONS, or the
89              IPv6  option  IPV6_PKTOPTIONS  or  IPV6_2292PKTOPTIONS  for  the
90              socket  this  value  is returned from inet:getopts/2 when called
91              with the option name pktoptions.
92
93          Note:
94              This option appears to be VERY Linux specific, and its existence
95              in  future  Linux kernel versions is also worrying since the op‐
96              tion is part of RFC 2292 which is since long (2003) obsoleted by
97              RFC  3542 that explicitly removes this possibility to get packet
98              information from a stream socket. For comparision:  it  has  ex‐
99              isted in FreeBSD but is now removed, at least since FreeBSD 10.
100
101
102       option_name() =
103           active | buffer | delay_send | deliver | dontroute |
104           exit_on_close | header | high_msgq_watermark |
105           high_watermark | keepalive | linger | low_msgq_watermark |
106           low_watermark | mode | nodelay | packet | packet_size |
107           pktoptions | priority |
108           {raw,
109            Protocol :: integer() >= 0,
110            OptionNum :: integer() >= 0,
111            ValueSpec ::
112                (ValueSize :: integer() >= 0) | (ValueBin :: binary())} |
113           recbuf | reuseaddr | send_timeout | send_timeout_close |
114           show_econnreset | sndbuf | tos | tclass | ttl | recvtos |
115           recvtclass | recvttl | pktoptions | ipv6_v6only
116
117       connect_option() =
118           {ip, inet:socket_address()} |
119           {fd, Fd :: integer() >= 0} |
120           {ifaddr, inet:socket_address()} |
121           inet:address_family() |
122           {port, inet:port_number()} |
123           {tcp_module, module()} |
124           {netns, file:filename_all()} |
125           {bind_to_device, binary()} |
126           option()
127
128       listen_option() =
129           {ip, inet:socket_address()} |
130           {fd, Fd :: integer() >= 0} |
131           {ifaddr, inet:socket_address()} |
132           inet:address_family() |
133           {port, inet:port_number()} |
134           {backlog, B :: integer() >= 0} |
135           {tcp_module, module()} |
136           {netns, file:filename_all()} |
137           {bind_to_device, binary()} |
138           option()
139
140       socket()
141
142              As returned by accept/1,2 and connect/3,4.
143

EXPORTS

145       accept(ListenSocket) -> {ok, Socket} | {error, Reason}
146
147       accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason}
148
149              Types:
150
151                 ListenSocket = socket()
152                   Returned by listen/2.
153                 Timeout = timeout()
154                 Socket = socket()
155                 Reason = closed | timeout | system_limit | inet:posix()
156
157              Accepts  an  incoming  connection request on a listening socket.
158              Socket must be a socket returned from listen/2.  Timeout  speci‐
159              fies a time-out value in milliseconds. Defaults to infinity.
160
161              Returns:
162
163                * {ok, Socket} if a connection is established
164
165                * {error, closed} if ListenSocket is closed
166
167                * {error,  timeout} if no connection is established within the
168                  specified time
169
170                * {error, system_limit} if all available ports in  the  Erlang
171                  emulator are in use
172
173                * A  POSIX  error  value  if  something  else  goes wrong, see
174                  inet(3) for possible error values
175
176              Packets can be sent to the returned socket Socket using  send/2.
177              Packets  sent  from  the  peer are delivered as messages (unless
178              {active, false} is specified in the option list for the  listen‐
179              ing  socket,  in  which  case  packets  are retrieved by calling
180              recv/2):
181
182              {tcp, Socket, Data}
183
184          Note:
185              The accept call does not have to be issued from the socket owner
186              process.  Using version 5.5.3 and higher of the emulator, multi‐
187              ple simultaneous accept calls can be issued from different  pro‐
188              cesses,  which  allows for a pool of acceptor processes handling
189              incoming connections.
190
191
192       close(Socket) -> ok
193
194              Types:
195
196                 Socket = socket()
197
198              Closes a TCP socket.
199
200              Note that in most implementations of TCP, doing a close does not
201              guarantee  that  any data sent is delivered to the recipient be‐
202              fore the close is detected at the remote side. If  you  want  to
203              guarantee  delivery  of  the data to the recipient there are two
204              common ways to achieve this.
205
206                * Use gen_tcp:shutdown(Sock, write) to  signal  that  no  more
207                  data  is to be sent and wait for the read side of the socket
208                  to be closed.
209
210                * Use the socket option {packet, N} (or something similar)  to
211                  make  it  possible  for the receiver to close the connection
212                  when it knowns it has received all the data.
213
214       connect(Address, Port, Options) -> {ok, Socket} | {error, Reason}
215
216       connect(Address, Port, Options, Timeout) ->
217                  {ok, Socket} | {error, Reason}
218
219              Types:
220
221                 Address = inet:socket_address() | inet:hostname()
222                 Port = inet:port_number()
223                 Options = [connect_option()]
224                 Timeout = timeout()
225                 Socket = socket()
226                 Reason = timeout | inet:posix()
227
228              Connects to a server on TCP port Port on the host  with  IP  ad‐
229              dress  Address.  Argument Address can be a hostname or an IP ad‐
230              dress.
231
232              The following options are available:
233
234                {ip, Address}:
235                  If the host has many network interfaces, this option  speci‐
236                  fies which one to use.
237
238                {ifaddr, Address}:
239                  Same  as  {ip, Address}. If the host has many network inter‐
240                  faces, this option specifies which one to use.
241
242                {fd, integer() >= 0}:
243                  If  a  socket  has  somehow  been  connected  without  using
244                  gen_tcp, use this option to pass the file descriptor for it.
245                  If {ip, Address} and/or {port,  port_number()}  is  combined
246                  with this option, the fd is bound to the specified interface
247                  and port before connecting. If these options are not  speci‐
248                  fied,  it  is assumed that the fd is already bound appropri‐
249                  ately.
250
251                inet:
252                  Sets up the socket for IPv4.
253
254                inet6:
255                  Sets up the socket for IPv6.
256
257                local:
258                  Sets up a Unix Domain Socket. See inet:local_address()
259
260                {port, Port}:
261                  Specifies which local port number to use.
262
263                {tcp_module, module()}:
264                  Overrides  which  callback  module  is  used.  Defaults   to
265                  inet_tcp for IPv4 and inet6_tcp for IPv6.
266
267                Opt:
268                  See inet:setopts/2.
269
270              Packets  can be sent to the returned socket Socket using send/2.
271              Packets sent from the peer are delivered as messages:
272
273              {tcp, Socket, Data}
274
275              If the socket is in {active, N} mode (see inet:setopts/2 for de‐
276              tails) and its message counter drops to 0, the following message
277              is delivered to indicate that the  socket  has  transitioned  to
278              passive ({active, false}) mode:
279
280              {tcp_passive, Socket}
281
282              If the socket is closed, the following message is delivered:
283
284              {tcp_closed, Socket}
285
286              If  an  error occurs on the socket, the following message is de‐
287              livered (unless {active, false} is specified in the option  list
288              for  the  socket, in which case packets are retrieved by calling
289              recv/2):
290
291              {tcp_error, Socket, Reason}
292
293              The optional Timeout parameter specifies a time-out in millisec‐
294              onds. Defaults to infinity.
295
296          Note:
297              Keep  in mind that if the underlying OS connect() call returns a
298              timeout, gen_tcp:connect will also return a timeout  (i.e.  {er‐
299              ror, etimedout}), even if a larger Timeout was specified.
300
301
302          Note:
303              The  default  values for options specified to connect can be af‐
304              fected by the Kernel configuration  parameter  inet_default_con‐
305              nect_options. For details, see inet(3).
306
307
308       controlling_process(Socket, Pid) -> ok | {error, Reason}
309
310              Types:
311
312                 Socket = socket()
313                 Pid = pid()
314                 Reason = closed | not_owner | badarg | inet:posix()
315
316              Assigns a new controlling process Pid to Socket. The controlling
317              process is the process that receives messages from  the  socket.
318              If  called  by  any  other  process than the current controlling
319              process, {error, not_owner} is returned. If the process  identi‐
320              fied by Pid is not an existing local pid, {error, badarg} is re‐
321              turned. {error, badarg} may also be returned in some cases  when
322              Socket is closed during the execution of this function.
323
324              If the socket is set in active mode, this function will transfer
325              any messages in the mailbox of the caller to the new controlling
326              process.  If  any  other  process is interacting with the socket
327              while the transfer is happening, the transfer may not work  cor‐
328              rectly  and messages may remain in the caller's mailbox. For in‐
329              stance changing the sockets active mode before the  transfer  is
330              complete may cause this.
331
332       listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}
333
334              Types:
335
336                 Port = inet:port_number()
337                 Options = [listen_option()]
338                 ListenSocket = socket()
339                 Reason = system_limit | inet:posix()
340
341              Sets up a socket to listen on port Port on the local host.
342
343              If  Port  == 0, the underlying OS assigns an available port num‐
344              ber, use inet:port/1 to retrieve it.
345
346              The following options are available:
347
348                list:
349                  Received Packet is delivered as a list.
350
351                binary:
352                  Received Packet is delivered as a binary.
353
354                {backlog, B}:
355                  B is an integer >= 0. The backlog value defines the  maximum
356                  length  that  the  queue of pending connections can grow to.
357                  Defaults to 5.
358
359                {ip, Address}:
360                  If the host has many network interfaces, this option  speci‐
361                  fies which one to listen on.
362
363                {port, Port}:
364                  Specifies which local port number to use.
365
366                {fd, Fd}:
367                  If  a  socket  has  somehow  been  connected  without  using
368                  gen_tcp, use this option to pass the file descriptor for it.
369
370                {ifaddr, Address}:
371                  Same as {ip, Address}. If the host has many  network  inter‐
372                  faces, this option specifies which one to use.
373
374                inet6:
375                  Sets up the socket for IPv6.
376
377                inet:
378                  Sets up the socket for IPv4.
379
380                {tcp_module, module()}:
381                  Overrides   which  callback  module  is  used.  Defaults  to
382                  inet_tcp for IPv4 and inet6_tcp for IPv6.
383
384                Opt:
385                  See inet:setopts/2.
386
387              The returned socket ListenSocket should be used in calls to  ac‐
388              cept/1,2 to accept incoming connection requests.
389
390          Note:
391              The  default  values  for options specified to listen can be af‐
392              fected by the Kernel configuration  parameter  inet_default_lis‐
393              ten_options. For details, see inet(3).
394
395
396       recv(Socket, Length) -> {ok, Packet} | {error, Reason}
397
398       recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason}
399
400              Types:
401
402                 Socket = socket()
403                 Length = integer() >= 0
404                 Timeout = timeout()
405                 Packet = string() | binary() | HttpPacket
406                 Reason = closed | timeout | inet:posix()
407                 HttpPacket = term()
408                   See the description of HttpPacket in erlang:decode_packet/3
409                   in ERTS.
410
411              Receives a packet from a socket in passive mode. A closed socket
412              is indicated by return value {error, closed}.
413
414              Argument  Length  is  only  meaningful when the socket is in raw
415              mode and denotes the number of bytes to read. If  Length  is  0,
416              all  available bytes are returned. If Length > 0, exactly Length
417              bytes are returned, or an error; possibly discarding  less  than
418              Length  bytes  of  data when the socket is closed from the other
419              side.
420
421              The optional Timeout parameter specifies a time-out in millisec‐
422              onds. Defaults to infinity.
423
424       send(Socket, Packet) -> ok | {error, Reason}
425
426              Types:
427
428                 Socket = socket()
429                 Packet = iodata()
430                 Reason = closed | inet:posix()
431
432              Sends a packet on a socket.
433
434              There  is no send call with a time-out option, use socket option
435              send_timeout if time-outs are desired. See section Examples.
436
437       shutdown(Socket, How) -> ok | {error, Reason}
438
439              Types:
440
441                 Socket = socket()
442                 How = read | write | read_write
443                 Reason = inet:posix()
444
445              Closes a socket in one or two directions.
446
447              How == write means closing the socket for writing, reading  from
448              it is still possible.
449
450              If  How  ==  read  or  there is no outgoing data buffered in the
451              Socket port, the socket is shut down immediately and  any  error
452              encountered is returned in Reason.
453
454              If  there  is  data  buffered in the socket port, the attempt to
455              shutdown the socket is postponed until that data is  written  to
456              the  kernel  socket  send buffer. If any errors are encountered,
457              the socket is closed and {error, closed} is returned on the next
458              recv/2 or send/2.
459
460              Option  {exit_on_close,  false} is useful if the peer has done a
461              shutdown on the write side.
462

EXAMPLES

464       The following example illustrates use of option {active,once} and  mul‐
465       tiple  accepts by implementing a server as a number of worker processes
466       doing accept on a single listening socket. Function start/2  takes  the
467       number  of  worker processes and the port number on which to listen for
468       incoming connections. If LPort is specified as  0,  an  ephemeral  port
469       number is used, which is why the start function returns the actual port
470       number allocated:
471
472       start(Num,LPort) ->
473           case gen_tcp:listen(LPort,[{active, false},{packet,2}]) of
474               {ok, ListenSock} ->
475                   start_servers(Num,ListenSock),
476                   {ok, Port} = inet:port(ListenSock),
477                   Port;
478               {error,Reason} ->
479                   {error,Reason}
480           end.
481
482       start_servers(0,_) ->
483           ok;
484       start_servers(Num,LS) ->
485           spawn(?MODULE,server,[LS]),
486           start_servers(Num-1,LS).
487
488       server(LS) ->
489           case gen_tcp:accept(LS) of
490               {ok,S} ->
491                   loop(S),
492                   server(LS);
493               Other ->
494                   io:format("accept returned ~w - goodbye!~n",[Other]),
495                   ok
496           end.
497
498       loop(S) ->
499           inet:setopts(S,[{active,once}]),
500           receive
501               {tcp,S,Data} ->
502                   Answer = process(Data), % Not implemented in this example
503                   gen_tcp:send(S,Answer),
504                   loop(S);
505               {tcp_closed,S} ->
506                   io:format("Socket ~w closed [~w]~n",[S,self()]),
507                   ok
508           end.
509
510       Example of a simple client:
511
512       client(PortNo,Message) ->
513           {ok,Sock} = gen_tcp:connect("localhost",PortNo,[{active,false},
514                                                           {packet,2}]),
515           gen_tcp:send(Sock,Message),
516           A = gen_tcp:recv(Sock,0),
517           gen_tcp:close(Sock),
518           A.
519
520       The send call does not accept a time-out option  because  time-outs  on
521       send  is  handled through socket option send_timeout. The behavior of a
522       send operation with no receiver is mainly defined by the underlying TCP
523       stack  and  the  network  infrastructure.  To write code that handles a
524       hanging receiver that can eventually cause the sender to hang on a send
525       do like the following.
526
527       Consider  a process that receives data from a client process to be for‐
528       warded to a server on the network. The  process  is  connected  to  the
529       server through TCP/IP and does not get any acknowledge for each message
530       it sends, but has to rely on the send time-out option  to  detect  that
531       the  other  end  is  unresponsive. Option send_timeout can be used when
532       connecting:
533
534       {ok,Sock} = gen_tcp:connect(HostAddress, Port,
535                                   [{active,false},
536                                    {send_timeout, 5000},
537                                    {packet,2}]),
538                       loop(Sock), % See below
539
540       In the loop where requests are handled, send time-outs can now  be  de‐
541       tected:
542
543       loop(Sock) ->
544           receive
545               {Client, send_data, Binary} ->
546                   case gen_tcp:send(Sock,[Binary]) of
547                       {error, timeout} ->
548                           io:format("Send timeout, closing!~n",
549                                     []),
550                           handle_send_timeout(), % Not implemented here
551                           Client ! {self(),{error_sending, timeout}},
552                           %% Usually, it's a good idea to give up in case of a
553                           %% send timeout, as you never know how much actually
554                           %% reached the server, maybe only a packet header?!
555                           gen_tcp:close(Sock);
556                       {error, OtherSendError} ->
557                           io:format("Some other error on socket (~p), closing",
558                                     [OtherSendError]),
559                           Client ! {self(),{error_sending, OtherSendError}},
560                           gen_tcp:close(Sock);
561                       ok ->
562                           Client ! {self(), data_sent},
563                           loop(Sock)
564                   end
565           end.
566
567       Usually  it  suffices to detect time-outs on receive, as most protocols
568       include some sort of acknowledgment from the server, but if the  proto‐
569       col is strictly one way, option send_timeout comes in handy.
570
571
572
573Ericsson AB                     kernel 7.3.1.1                      gen_tcp(3)
Impressum