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 |
62           binary |
63           {nodelay, boolean()} |
64           {packet,
65            0 |
66            1 |
67            2 |
68            4 |
69            raw |
70            sunrm |
71            asn1 |
72            cdr |
73            fcgi |
74            line |
75            tpkt |
76            http |
77            httph |
78            http_bin |
79            httph_bin} |
80           {packet_size, integer() >= 0} |
81           {priority, integer() >= 0} |
82           {raw,
83            Protocol :: integer() >= 0,
84            OptionNum :: integer() >= 0,
85            ValueBin :: binary()} |
86           {recbuf, integer() >= 0} |
87           {reuseaddr, boolean()} |
88           {send_timeout, integer() >= 0 | infinity} |
89           {send_timeout_close, boolean()} |
90           {show_econnreset, boolean()} |
91           {sndbuf, integer() >= 0} |
92           {tos, integer() >= 0} |
93           {ipv6_v6only, boolean()}
94
95       option_name() =
96           active |
97           buffer |
98           delay_send |
99           deliver |
100           dontroute |
101           exit_on_close |
102           header |
103           high_msgq_watermark |
104           high_watermark |
105           keepalive |
106           linger |
107           low_msgq_watermark |
108           low_watermark |
109           mode |
110           nodelay |
111           packet |
112           packet_size |
113           priority |
114           {raw,
115            Protocol :: integer() >= 0,
116            OptionNum :: integer() >= 0,
117            ValueSpec ::
118                (ValueSize :: integer() >= 0) | (ValueBin :: binary())} |
119           recbuf |
120           reuseaddr |
121           send_timeout |
122           send_timeout_close |
123           show_econnreset |
124           sndbuf |
125           tos |
126           ipv6_v6only
127
128       connect_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           {tcp_module, module()} |
135           option()
136
137       listen_option() =
138           {ip, inet:socket_address()} |
139           {fd, Fd :: integer() >= 0} |
140           {ifaddr, inet:socket_address()} |
141           inet:address_family() |
142           {port, inet:port_number()} |
143           {backlog, B :: integer() >= 0} |
144           {tcp_module, module()} |
145           option()
146
147       socket()
148
149              As returned by accept/1,2 and connect/3,4.
150

EXPORTS

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

EXAMPLES

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