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 |
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 {tclass, integer() >= 0} |
94 {ttl, integer() >= 0} |
95 {recvtos, boolean()} |
96 {recvtclass, boolean()} |
97 {recvttl, boolean()} |
98 {ipv6_v6only, boolean()}
99
100 pktoptions_value() = {pktoptions, inet:ancillary_data()}
101
102 If the platform implements the IPv4 option IP_PKTOPTIONS, or the
103 IPv6 option IPV6_PKTOPTIONS or IPV6_2292PKTOPTIONS for the
104 socket this value is returned from inet:getopts/2 when called
105 with the option name pktoptions.
106
107 Note:
108 This option appears to be VERY Linux specific, and its existence
109 in future Linux kernel versions is also worrying since the
110 option is part of RFC 2292 which is since long (2003) obsoleted
111 by RFC 3542 that explicitly removes this possibility to get
112 packet information from a stream socket. For comparision: it has
113 existed in FreeBSD but is now removed, at least since FreeBSD
114 10.
115
116
117 option_name() =
118 active |
119 buffer |
120 delay_send |
121 deliver |
122 dontroute |
123 exit_on_close |
124 header |
125 high_msgq_watermark |
126 high_watermark |
127 keepalive |
128 linger |
129 low_msgq_watermark |
130 low_watermark |
131 mode |
132 nodelay |
133 packet |
134 packet_size |
135 pktoptions |
136 priority |
137 {raw,
138 Protocol :: integer() >= 0,
139 OptionNum :: integer() >= 0,
140 ValueSpec ::
141 (ValueSize :: integer() >= 0) | (ValueBin :: binary())} |
142 recbuf |
143 reuseaddr |
144 send_timeout |
145 send_timeout_close |
146 show_econnreset |
147 sndbuf |
148 tos |
149 tclass |
150 ttl |
151 recvtos |
152 recvtclass |
153 recvttl |
154 pktoptions |
155 ipv6_v6only
156
157 connect_option() =
158 {ip, inet:socket_address()} |
159 {fd, Fd :: integer() >= 0} |
160 {ifaddr, inet:socket_address()} |
161 inet:address_family() |
162 {port, inet:port_number()} |
163 {tcp_module, module()} |
164 {netns, file:filename_all()} |
165 {bind_to_device, binary()} |
166 option()
167
168 listen_option() =
169 {ip, inet:socket_address()} |
170 {fd, Fd :: integer() >= 0} |
171 {ifaddr, inet:socket_address()} |
172 inet:address_family() |
173 {port, inet:port_number()} |
174 {backlog, B :: integer() >= 0} |
175 {tcp_module, module()} |
176 {netns, file:filename_all()} |
177 {bind_to_device, binary()} |
178 option()
179
180 socket()
181
182 As returned by accept/1,2 and connect/3,4.
183
185 accept(ListenSocket) -> {ok, Socket} | {error, Reason}
186
187 accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason}
188
189 Types:
190
191 ListenSocket = socket()
192 Returned by listen/2.
193 Timeout = timeout()
194 Socket = socket()
195 Reason = closed | timeout | system_limit | inet:posix()
196
197 Accepts an incoming connection request on a listening socket.
198 Socket must be a socket returned from listen/2. Timeout speci‐
199 fies a time-out value in milliseconds. Defaults to infinity.
200
201 Returns:
202
203 * {ok, Socket} if a connection is established
204
205 * {error, closed} if ListenSocket is closed
206
207 * {error, timeout} if no connection is established within the
208 specified time
209
210 * {error, system_limit} if all available ports in the Erlang
211 emulator are in use
212
213 * A POSIX error value if something else goes wrong, see
214 inet(3) for possible error values
215
216 Packets can be sent to the returned socket Socket using send/2.
217 Packets sent from the peer are delivered as messages (unless
218 {active, false} is specified in the option list for the listen‐
219 ing socket, in which case packets are retrieved by calling
220 recv/2):
221
222 {tcp, Socket, Data}
223
224 Note:
225 The accept call does not have to be issued from the socket owner
226 process. Using version 5.5.3 and higher of the emulator, multi‐
227 ple simultaneous accept calls can be issued from different pro‐
228 cesses, which allows for a pool of acceptor processes handling
229 incoming connections.
230
231
232 close(Socket) -> ok
233
234 Types:
235
236 Socket = socket()
237
238 Closes a TCP socket.
239
240 Note that in most implementations of TCP, doing a close does not
241 guarantee that any data sent is delivered to the recipient
242 before the close is detected at the remote side. If you want to
243 guarantee delivery of the data to the recipient there are two
244 common ways to achieve this.
245
246 * Use gen_tcp:shutdown(Sock, write) to signal that no more
247 data is to be sent and wait for the read side of the socket
248 to be closed.
249
250 * Use the socket option {packet, N} (or something similar) to
251 make it possible for the receiver to close the connection
252 when it knowns it has received all the data.
253
254 connect(Address, Port, Options) -> {ok, Socket} | {error, Reason}
255
256 connect(Address, Port, Options, Timeout) ->
257 {ok, Socket} | {error, Reason}
258
259 Types:
260
261 Address = inet:socket_address() | inet:hostname()
262 Port = inet:port_number()
263 Options = [connect_option()]
264 Timeout = timeout()
265 Socket = socket()
266 Reason = inet:posix()
267
268 Connects to a server on TCP port Port on the host with IP
269 address Address. Argument Address can be a hostname or an IP
270 address.
271
272 The following options are available:
273
274 {ip, Address}:
275 If the host has many network interfaces, this option speci‐
276 fies which one to use.
277
278 {ifaddr, Address}:
279 Same as {ip, Address}. If the host has many network inter‐
280 faces, this option specifies which one to use.
281
282 {fd, integer() >= 0}:
283 If a socket has somehow been connected without using
284 gen_tcp, use this option to pass the file descriptor for it.
285 If {ip, Address} and/or {port, port_number()} is combined
286 with this option, the fd is bound to the specified interface
287 and port before connecting. If these options are not speci‐
288 fied, it is assumed that the fd is already bound appropri‐
289 ately.
290
291 inet:
292 Sets up the socket for IPv4.
293
294 inet6:
295 Sets up the socket for IPv6.
296
297 local:
298 Sets up a Unix Domain Socket. See inet:local_address()
299
300 {port, Port}:
301 Specifies which local port number to use.
302
303 {tcp_module, module()}:
304 Overrides which callback module is used. Defaults to
305 inet_tcp for IPv4 and inet6_tcp for IPv6.
306
307 Opt:
308 See inet:setopts/2.
309
310 Packets can be sent to the returned socket Socket using send/2.
311 Packets sent from the peer are delivered as messages:
312
313 {tcp, Socket, Data}
314
315 If the socket is in {active, N} mode (see inet:setopts/2 for
316 details) and its message counter drops to 0, the following mes‐
317 sage is delivered to indicate that the socket has transitioned
318 to passive ({active, false}) mode:
319
320 {tcp_passive, Socket}
321
322 If the socket is closed, the following message is delivered:
323
324 {tcp_closed, Socket}
325
326 If an error occurs on the socket, the following message is
327 delivered (unless {active, false} is specified in the option
328 list for the socket, in which case packets are retrieved by
329 calling recv/2):
330
331 {tcp_error, Socket, Reason}
332
333 The optional Timeout parameter specifies a time-out in millisec‐
334 onds. Defaults to infinity.
335
336 Note:
337 The default values for options specified to connect can be
338 affected by the Kernel configuration parameter inet_default_con‐
339 nect_options. For details, see inet(3).
340
341
342 controlling_process(Socket, Pid) -> ok | {error, Reason}
343
344 Types:
345
346 Socket = socket()
347 Pid = pid()
348 Reason = closed | not_owner | badarg | inet:posix()
349
350 Assigns a new controlling process Pid to Socket. The controlling
351 process is the process that receives messages from the socket.
352 If called by any other process than the current controlling
353 process, {error, not_owner} is returned. If the process identi‐
354 fied by Pid is not an existing local pid, {error, badarg} is
355 returned. {error, badarg} may also be returned in some cases
356 when Socket is closed during the execution of this function.
357
358 If the socket is set in active mode, this function will transfer
359 any messages in the mailbox of the caller to the new controlling
360 process. If any other process is interacting with the socket
361 while the transfer is happening, the transfer may not work cor‐
362 rectly and messages may remain in the caller's mailbox. For
363 instance changing the sockets active mode before the transfere
364 is complete may cause this.
365
366 listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}
367
368 Types:
369
370 Port = inet:port_number()
371 Options = [listen_option()]
372 ListenSocket = socket()
373 Reason = system_limit | inet:posix()
374
375 Sets up a socket to listen on port Port on the local host.
376
377 If Port == 0, the underlying OS assigns an available port num‐
378 ber, use inet:port/1 to retrieve it.
379
380 The following options are available:
381
382 list:
383 Received Packet is delivered as a list.
384
385 binary:
386 Received Packet is delivered as a binary.
387
388 {backlog, B}:
389 B is an integer >= 0. The backlog value defines the maximum
390 length that the queue of pending connections can grow to.
391 Defaults to 5.
392
393 {ip, Address}:
394 If the host has many network interfaces, this option speci‐
395 fies which one to listen on.
396
397 {port, Port}:
398 Specifies which local port number to use.
399
400 {fd, Fd}:
401 If a socket has somehow been connected without using
402 gen_tcp, use this option to pass the file descriptor for it.
403
404 {ifaddr, Address}:
405 Same as {ip, Address}. If the host has many network inter‐
406 faces, this option specifies which one to use.
407
408 inet6:
409 Sets up the socket for IPv6.
410
411 inet:
412 Sets up the socket for IPv4.
413
414 {tcp_module, module()}:
415 Overrides which callback module is used. Defaults to
416 inet_tcp for IPv4 and inet6_tcp for IPv6.
417
418 Opt:
419 See inet:setopts/2.
420
421 The returned socket ListenSocket should be used in calls to
422 accept/1,2 to accept incoming connection requests.
423
424 Note:
425 The default values for options specified to listen can be
426 affected by the Kernel configuration parameter inet_default_lis‐
427 ten_options. For details, see inet(3).
428
429
430 recv(Socket, Length) -> {ok, Packet} | {error, Reason}
431
432 recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason}
433
434 Types:
435
436 Socket = socket()
437 Length = integer() >= 0
438 Timeout = timeout()
439 Packet = string() | binary() | HttpPacket
440 Reason = closed | inet:posix()
441 HttpPacket = term()
442 See the description of HttpPacket in erlang:decode_packet/3
443 in ERTS.
444
445 Receives a packet from a socket in passive mode. A closed socket
446 is indicated by return value {error, closed}.
447
448 Argument Length is only meaningful when the socket is in raw
449 mode and denotes the number of bytes to read. If Length is 0,
450 all available bytes are returned. If Length > 0, exactly Length
451 bytes are returned, or an error; possibly discarding less than
452 Length bytes of data when the socket is closed from the other
453 side.
454
455 The optional Timeout parameter specifies a time-out in millisec‐
456 onds. Defaults to infinity.
457
458 send(Socket, Packet) -> ok | {error, Reason}
459
460 Types:
461
462 Socket = socket()
463 Packet = iodata()
464 Reason = closed | inet:posix()
465
466 Sends a packet on a socket.
467
468 There is no send call with a time-out option, use socket option
469 send_timeout if time-outs are desired. See section Examples.
470
471 shutdown(Socket, How) -> ok | {error, Reason}
472
473 Types:
474
475 Socket = socket()
476 How = read | write | read_write
477 Reason = inet:posix()
478
479 Closes a socket in one or two directions.
480
481 How == write means closing the socket for writing, reading from
482 it is still possible.
483
484 If How == read or there is no outgoing data buffered in the
485 Socket port, the socket is shut down immediately and any error
486 encountered is returned in Reason.
487
488 If there is data buffered in the socket port, the attempt to
489 shutdown the socket is postponed until that data is written to
490 the kernel socket send buffer. If any errors are encountered,
491 the socket is closed and {error, closed} is returned on the next
492 recv/2 or send/2.
493
494 Option {exit_on_close, false} is useful if the peer has done a
495 shutdown on the write side.
496
498 The following example illustrates use of option {active,once} and mul‐
499 tiple accepts by implementing a server as a number of worker processes
500 doing accept on a single listening socket. Function start/2 takes the
501 number of worker processes and the port number on which to listen for
502 incoming connections. If LPort is specified as 0, an ephemeral port
503 number is used, which is why the start function returns the actual port
504 number allocated:
505
506 start(Num,LPort) ->
507 case gen_tcp:listen(LPort,[{active, false},{packet,2}]) of
508 {ok, ListenSock} ->
509 start_servers(Num,ListenSock),
510 {ok, Port} = inet:port(ListenSock),
511 Port;
512 {error,Reason} ->
513 {error,Reason}
514 end.
515
516 start_servers(0,_) ->
517 ok;
518 start_servers(Num,LS) ->
519 spawn(?MODULE,server,[LS]),
520 start_servers(Num-1,LS).
521
522 server(LS) ->
523 case gen_tcp:accept(LS) of
524 {ok,S} ->
525 loop(S),
526 server(LS);
527 Other ->
528 io:format("accept returned ~w - goodbye!~n",[Other]),
529 ok
530 end.
531
532 loop(S) ->
533 inet:setopts(S,[{active,once}]),
534 receive
535 {tcp,S,Data} ->
536 Answer = process(Data), % Not implemented in this example
537 gen_tcp:send(S,Answer),
538 loop(S);
539 {tcp_closed,S} ->
540 io:format("Socket ~w closed [~w]~n",[S,self()]),
541 ok
542 end.
543
544 Example of a simple client:
545
546 client(PortNo,Message) ->
547 {ok,Sock} = gen_tcp:connect("localhost",PortNo,[{active,false},
548 {packet,2}]),
549 gen_tcp:send(Sock,Message),
550 A = gen_tcp:recv(Sock,0),
551 gen_tcp:close(Sock),
552 A.
553
554 The send call does not accept a time-out option because time-outs on
555 send is handled through socket option send_timeout. The behavior of a
556 send operation with no receiver is mainly defined by the underlying TCP
557 stack and the network infrastructure. To write code that handles a
558 hanging receiver that can eventually cause the sender to hang on a send
559 do like the following.
560
561 Consider a process that receives data from a client process to be for‐
562 warded to a server on the network. The process is connected to the
563 server through TCP/IP and does not get any acknowledge for each message
564 it sends, but has to rely on the send time-out option to detect that
565 the other end is unresponsive. Option send_timeout can be used when
566 connecting:
567
568 {ok,Sock} = gen_tcp:connect(HostAddress, Port,
569 [{active,false},
570 {send_timeout, 5000},
571 {packet,2}]),
572 loop(Sock), % See below
573
574 In the loop where requests are handled, send time-outs can now be
575 detected:
576
577 loop(Sock) ->
578 receive
579 {Client, send_data, Binary} ->
580 case gen_tcp:send(Sock,[Binary]) of
581 {error, timeout} ->
582 io:format("Send timeout, closing!~n",
583 []),
584 handle_send_timeout(), % Not implemented here
585 Client ! {self(),{error_sending, timeout}},
586 %% Usually, it's a good idea to give up in case of a
587 %% send timeout, as you never know how much actually
588 %% reached the server, maybe only a packet header?!
589 gen_tcp:close(Sock);
590 {error, OtherSendError} ->
591 io:format("Some other error on socket (~p), closing",
592 [OtherSendError]),
593 Client ! {self(),{error_sending, OtherSendError}},
594 gen_tcp:close(Sock);
595 ok ->
596 Client ! {self(), data_sent},
597 loop(Sock)
598 end
599 end.
600
601 Usually it suffices to detect time-outs on receive, as most protocols
602 include some sort of acknowledgment from the server, but if the proto‐
603 col is strictly one way, option send_timeout comes in handy.
604
605
606
607Ericsson AB kernel 6.3.1.1 gen_tcp(3)