1gen_tcp(3) Erlang Module Definition gen_tcp(3)
2
3
4
6 gen_tcp - Interface to TCP/IP sockets.
7
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
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
96 option is part of RFC 2292 which is since long (2003) obsoleted
97 by RFC 3542 that explicitly removes this possibility to get
98 packet information from a stream socket. For comparision: it has
99 existed in FreeBSD but is now removed, at least since FreeBSD
100 10.
101
102
103 option_name() =
104 active | buffer | delay_send | deliver | dontroute |
105 exit_on_close | header | high_msgq_watermark |
106 high_watermark | keepalive | linger | low_msgq_watermark |
107 low_watermark | mode | nodelay | packet | packet_size |
108 pktoptions | priority |
109 {raw,
110 Protocol :: integer() >= 0,
111 OptionNum :: integer() >= 0,
112 ValueSpec ::
113 (ValueSize :: integer() >= 0) | (ValueBin :: binary())} |
114 recbuf | reuseaddr | send_timeout | send_timeout_close |
115 show_econnreset | sndbuf | tos | tclass | ttl | recvtos |
116 recvtclass | recvttl | pktoptions | ipv6_v6only
117
118 connect_option() =
119 {ip, inet:socket_address()} |
120 {fd, Fd :: integer() >= 0} |
121 {ifaddr, inet:socket_address()} |
122 inet:address_family() |
123 {port, inet:port_number()} |
124 {tcp_module, module()} |
125 {netns, file:filename_all()} |
126 {bind_to_device, binary()} |
127 option()
128
129 listen_option() =
130 {ip, inet:socket_address()} |
131 {fd, Fd :: integer() >= 0} |
132 {ifaddr, inet:socket_address()} |
133 inet:address_family() |
134 {port, inet:port_number()} |
135 {backlog, B :: integer() >= 0} |
136 {tcp_module, module()} |
137 {netns, file:filename_all()} |
138 {bind_to_device, binary()} |
139 option()
140
141 socket()
142
143 As returned by accept/1,2 and connect/3,4.
144
146 accept(ListenSocket) -> {ok, Socket} | {error, Reason}
147
148 accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason}
149
150 Types:
151
152 ListenSocket = socket()
153 Returned by listen/2.
154 Timeout = timeout()
155 Socket = socket()
156 Reason = closed | timeout | system_limit | inet:posix()
157
158 Accepts an incoming connection request on a listening socket.
159 Socket must be a socket returned from listen/2. Timeout speci‐
160 fies a time-out value in milliseconds. Defaults to infinity.
161
162 Returns:
163
164 * {ok, Socket} if a connection is established
165
166 * {error, closed} if ListenSocket is closed
167
168 * {error, timeout} if no connection is established within the
169 specified time
170
171 * {error, system_limit} if all available ports in the Erlang
172 emulator are in use
173
174 * A POSIX error value if something else goes wrong, see
175 inet(3) for possible error values
176
177 Packets can be sent to the returned socket Socket using send/2.
178 Packets sent from the peer are delivered as messages (unless
179 {active, false} is specified in the option list for the listen‐
180 ing socket, in which case packets are retrieved by calling
181 recv/2):
182
183 {tcp, Socket, Data}
184
185 Note:
186 The accept call does not have to be issued from the socket owner
187 process. Using version 5.5.3 and higher of the emulator, multi‐
188 ple simultaneous accept calls can be issued from different pro‐
189 cesses, which allows for a pool of acceptor processes handling
190 incoming connections.
191
192
193 close(Socket) -> ok
194
195 Types:
196
197 Socket = socket()
198
199 Closes a TCP socket.
200
201 Note that in most implementations of TCP, doing a close does not
202 guarantee that any data sent is delivered to the recipient
203 before the close is detected at the remote side. If you want to
204 guarantee delivery of the data to the recipient there are two
205 common ways to achieve this.
206
207 * Use gen_tcp:shutdown(Sock, write) to signal that no more
208 data is to be sent and wait for the read side of the socket
209 to be closed.
210
211 * Use the socket option {packet, N} (or something similar) to
212 make it possible for the receiver to close the connection
213 when it knowns it has received all the data.
214
215 connect(Address, Port, Options) -> {ok, Socket} | {error, Reason}
216
217 connect(Address, Port, Options, Timeout) ->
218 {ok, Socket} | {error, Reason}
219
220 Types:
221
222 Address = inet:socket_address() | inet:hostname()
223 Port = inet:port_number()
224 Options = [connect_option()]
225 Timeout = timeout()
226 Socket = socket()
227 Reason = timeout | inet:posix()
228
229 Connects to a server on TCP port Port on the host with IP
230 address Address. Argument Address can be a hostname or an IP
231 address.
232
233 The following options are available:
234
235 {ip, Address}:
236 If the host has many network interfaces, this option speci‐
237 fies which one to use.
238
239 {ifaddr, Address}:
240 Same as {ip, Address}. If the host has many network inter‐
241 faces, this option specifies which one to use.
242
243 {fd, integer() >= 0}:
244 If a socket has somehow been connected without using
245 gen_tcp, use this option to pass the file descriptor for it.
246 If {ip, Address} and/or {port, port_number()} is combined
247 with this option, the fd is bound to the specified interface
248 and port before connecting. If these options are not speci‐
249 fied, it is assumed that the fd is already bound appropri‐
250 ately.
251
252 inet:
253 Sets up the socket for IPv4.
254
255 inet6:
256 Sets up the socket for IPv6.
257
258 local:
259 Sets up a Unix Domain Socket. See inet:local_address()
260
261 {port, Port}:
262 Specifies which local port number to use.
263
264 {tcp_module, module()}:
265 Overrides which callback module is used. Defaults to
266 inet_tcp for IPv4 and inet6_tcp for IPv6.
267
268 Opt:
269 See inet:setopts/2.
270
271 Packets can be sent to the returned socket Socket using send/2.
272 Packets sent from the peer are delivered as messages:
273
274 {tcp, Socket, Data}
275
276 If the socket is in {active, N} mode (see inet:setopts/2 for
277 details) and its message counter drops to 0, the following mes‐
278 sage is delivered to indicate that the socket has transitioned
279 to passive ({active, false}) mode:
280
281 {tcp_passive, Socket}
282
283 If the socket is closed, the following message is delivered:
284
285 {tcp_closed, Socket}
286
287 If an error occurs on the socket, the following message is
288 delivered (unless {active, false} is specified in the option
289 list for the socket, in which case packets are retrieved by
290 calling recv/2):
291
292 {tcp_error, Socket, Reason}
293
294 The optional Timeout parameter specifies a time-out in millisec‐
295 onds. Defaults to infinity.
296
297 Note:
298 Keep in mind that if the underlying OS connect() call returns a
299 timeout, gen_tcp:connect will also return a timeout (i.e.
300 {error, etimedout}), even if a larger Timeout was specified.
301
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 | timeout | 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
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 6.5.2 gen_tcp(3)