Erlang -- gen_tcp

Kernel

Reference Manual

Version 6.1

- User's Guide
- Reference Manual
- Release Notes
- PDF
- Top

- Expand All
- Contract All

### Table of Contents

- kernel (App)
- app
- application
  - Top of manual page
  - ensure_all_started/1
  - ensure_all_started/2
  - ensure_started/1
  - ensure_started/2
  - get_all_env/0
  - get_all_env/1
  - get_all_key/0
  - get_all_key/1
  - get_application/0
  - get_application/1
  - get_env/1
  - get_env/2
  - get_env/3
  - get_key/1
  - get_key/2
  - load/1
  - load/2
  - loaded_applications/0
  - permit/2
  - set_env/3
  - set_env/4
  - start/1
  - start/2
  - start_type/0
  - stop/1
  - takeover/2
  - unload/1
  - unset_env/2
  - unset_env/3
  - which_applications/0
  - which_applications/1
  - Module:config_change/3
  - Module:prep_stop/1
  - Module:start/2
  - Module:start_phase/3
  - Module:stop/1
- auth
  - Top of manual page
  - cookie/0
  - cookie/1
  - is_auth/1
  - node_cookie/1
  - node_cookie/2
- code
  - Top of manual page
  - add_path/1
  - add_patha/1
  - add_paths/1
  - add_pathsa/1
  - add_pathsz/1
  - add_pathz/1
  - all_loaded/0
  - atomic_load/1
  - clash/0
  - compiler_dir/0
  - del_path/1
  - delete/1
  - ensure_loaded/1
  - ensure_modules_loaded/1
  - finish_loading/1
  - get_mode/0
  - get_object_code/1
  - get_path/0
  - is_loaded/1
  - is_module_native/1
  - is_sticky/1
  - lib_dir/0
  - lib_dir/1
  - lib_dir/2
  - load_abs/1
  - load_binary/3
  - load_file/1
  - modified_modules/0
  - module_status/1
  - objfile_extension/0
  - prepare_loading/1
  - priv_dir/1
  - purge/1
  - replace_path/2
  - root_dir/0
  - set_path/1
  - soft_purge/1
  - stick_dir/1
  - unstick_dir/1
  - where_is_file/1
  - which/1
- config
- disk_log
  - Top of manual page
  - accessible_logs/0
  - alog/2
  - alog_terms/2
  - balog/2
  - balog_terms/2
  - bchunk/2
  - bchunk/3
  - block/1
  - block/2
  - blog/2
  - blog_terms/2
  - breopen/3
  - btruncate/2
  - change_header/2
  - change_notify/3
  - change_size/2
  - chunk/2
  - chunk/3
  - chunk_info/1
  - chunk_step/3
  - close/1
  - format_error/1
  - inc_wrap_file/1
  - info/1
  - lclose/1
  - lclose/2
  - log/2
  - log_terms/2
  - open/1
  - pid2name/1
  - reopen/2
  - reopen/3
  - sync/1
  - truncate/1
  - truncate/2
  - unblock/1
- erl_boot_server
  - Top of manual page
  - add_slave/1
  - delete_slave/1
  - start/1
  - start_link/1
  - which_slaves/0
- erl_ddll
  - Top of manual page
  - demonitor/1
  - format_error/1
  - info/0
  - info/1
  - info/2
  - load/2
  - load_driver/2
  - loaded_drivers/0
  - monitor/2
  - reload/2
  - reload_driver/2
  - try_load/3
  - try_unload/2
  - unload/1
  - unload_driver/1
- erl_epmd
  - Top of manual page
  - address_please/3
  - names/1
  - port_please/2
  - port_please/3
  - register_node/2
  - register_node/3
  - start_link/0
- erl_prim_loader
- erlang
- error_handler
  - Top of manual page
  - raise_undef_exception/3
  - undefined_function/3
  - undefined_lambda/3
- error_logger
  - Top of manual page
  - add_report_handler/1
  - add_report_handler/2
  - delete_report_handler/1
  - error_msg/1
  - error_msg/2
  - error_report/1
  - error_report/2
  - format/2
  - get_format_depth/0
  - info_msg/1
  - info_msg/2
  - info_report/1
  - info_report/2
  - logfile/1
  - tty/1
  - warning_map/0
  - warning_msg/1
  - warning_msg/2
  - warning_report/1
  - warning_report/2
- file
  - Top of manual page
  - advise/4
  - allocate/3
  - change_group/2
  - change_mode/2
  - change_owner/2
  - change_owner/3
  - change_time/2
  - change_time/3
  - close/1
  - consult/1
  - copy/2
  - copy/3
  - datasync/1
  - del_dir/1
  - delete/1
  - eval/1
  - eval/2
  - format_error/1
  - get_cwd/0
  - get_cwd/1
  - list_dir/1
  - list_dir_all/1
  - make_dir/1
  - make_link/2
  - make_symlink/2
  - native_name_encoding/0
  - open/2
  - path_consult/2
  - path_eval/2
  - path_open/3
  - path_script/2
  - path_script/3
  - pid2name/1
  - position/2
  - pread/2
  - pread/3
  - pwrite/2
  - pwrite/3
  - read/2
  - read_file/1
  - read_file_info/1
  - read_file_info/2
  - read_line/1
  - read_link/1
  - read_link_all/1
  - read_link_info/1
  - read_link_info/2
  - rename/2
  - script/1
  - script/2
  - sendfile/2
  - sendfile/5
  - set_cwd/1
  - sync/1
  - truncate/1
  - write/2
  - write_file/2
  - write_file/3
  - write_file_info/2
  - write_file_info/3
- gen_sctp
  - Top of manual page
  - abort/2
  - close/1
  - connect/4
  - connect/5
  - connect_init/4
  - connect_init/5
  - controlling_process/2
  - eof/2
  - error_string/1
  - listen/2
  - open/0
  - open/1
  - open/2
  - peeloff/2
  - recv/1
  - recv/2
  - send/3
  - send/4
- gen_tcp
  - Top of manual page
  - accept/1
  - accept/2
  - close/1
  - connect/3
  - connect/4
  - controlling_process/2
  - listen/2
  - recv/2
  - recv/3
  - send/2
  - shutdown/2
- gen_udp
  - Top of manual page
  - close/1
  - controlling_process/2
  - open/1
  - open/2
  - recv/2
  - recv/3
  - send/4
- global
  - Top of manual page
  - del_lock/1
  - del_lock/2
  - notify_all_name/3
  - random_exit_name/3
  - random_notify_name/3
  - re_register_name/2
  - re_register_name/3
  - register_name/2
  - register_name/3
  - registered_names/0
  - send/2
  - set_lock/1
  - set_lock/2
  - set_lock/3
  - sync/0
  - trans/2
  - trans/3
  - trans/4
  - unregister_name/1
  - whereis_name/1
- global_group
  - Top of manual page
  - global_groups/0
  - info/0
  - monitor_nodes/1
  - own_nodes/0
  - registered_names/1
  - send/2
  - send/3
  - sync/0
  - whereis_name/1
  - whereis_name/2
- heart
  - Top of manual page
  - clear_callback/0
  - clear_cmd/0
  - get_callback/0
  - get_cmd/0
  - get_options/0
  - set_callback/2
  - set_cmd/1
  - set_options/1
- inet
  - Top of manual page
  - close/1
  - format_error/1
  - get_rc/0
  - getaddr/2
  - getaddrs/2
  - gethostbyaddr/1
  - gethostbyname/1
  - gethostbyname/2
  - gethostname/0
  - getifaddrs/0
  - getopts/2
  - getstat/1
  - getstat/2
  - i/0
  - i/1
  - i/2
  - ipv4_mapped_ipv6_address/1
  - ntoa/1
  - parse_address/1
  - parse_ipv4_address/1
  - parse_ipv4strict_address/1
  - parse_ipv6_address/1
  - parse_ipv6strict_address/1
  - parse_strict_address/1
  - peername/1
  - peernames/1
  - peernames/2
  - port/1
  - setopts/2
  - sockname/1
  - socknames/1
  - socknames/2
- inet_res
  - Top of manual page
  - getbyname/2
  - getbyname/3
  - gethostbyaddr/1
  - gethostbyaddr/2
  - gethostbyname/1
  - gethostbyname/2
  - gethostbyname/3
  - lookup/3
  - lookup/4
  - lookup/5
  - nnslookup/4
  - nnslookup/5
  - nslookup/3
  - nslookup/4
  - resolve/3
  - resolve/4
  - resolve/5
- init
- logger
  - Top of manual page
  - add_handler/3
  - add_handler_filter/3
  - add_handlers/1
  - add_primary_filter/2
  - alert/1
  - alert/2
  - alert/2
  - compare_levels/2
  - critical/1
  - critical/2
  - critical/2
  - debug/1
  - debug/2
  - debug/2
  - emergency/1
  - emergency/2
  - emergency/2
  - error/1
  - error/2
  - error/2
  - format_report/1
  - get_config/0
  - get_handler_config/0
  - get_handler_config/1
  - get_handler_ids/0
  - get_module_level/0
  - get_module_level/1
  - get_primary_config/0
  - get_process_metadata/0
  - info/1
  - info/2
  - info/2
  - log/2
  - log/3
  - log/4
  - notice/1
  - notice/2
  - notice/2
  - remove_handler/1
  - remove_handler_filter/2
  - remove_primary_filter/1
  - set_application_level/2
  - set_handler_config/2
  - set_handler_config/3
  - set_module_level/2
  - set_primary_config/1
  - set_primary_config/2
  - set_process_metadata/1
  - unset_application_level/1
  - unset_module_level/0
  - unset_module_level/1
  - unset_process_metadata/0
  - update_formatter_config/2
  - update_formatter_config/3
  - update_handler_config/2
  - update_primary_config/1
  - update_process_metadata/1
  - warning/1
  - warning/2
  - warning/2
  - FModule:check_config/1
  - FModule:format/2
  - HModule:adding_handler/1
  - HModule:changing_config/2
  - HModule:log/2
  - HModule:removing_handler/1
- logger_filters
  - Top of manual page
  - domain/2
  - level/2
  - progress/2
  - remote_gl/2
- logger_formatter
  - Top of manual page
  - check_config/1
  - format/2
- logger_std_h
  - Top of manual page
  - filesync/1
- logger_disk_log_h
  - Top of manual page
  - filesync/1
- net_adm
  - Top of manual page
  - dns_hostname/1
  - host_file/0
  - localhost/0
  - names/0
  - names/1
  - ping/1
  - world/0
  - world/1
  - world_list/1
  - world_list/2
- net_kernel
  - Top of manual page
  - allow/1
  - connect_node/1
  - get_net_ticktime/0
  - getopts/2
  - monitor_nodes/1
  - monitor_nodes/2
  - set_net_ticktime/1
  - set_net_ticktime/2
  - setopts/2
  - start/1
  - start/1
  - start/1
  - stop/0
- os
  - Top of manual page
  - cmd/1
  - cmd/2
  - find_executable/1
  - find_executable/2
  - getenv/0
  - getenv/1
  - getenv/2
  - getpid/0
  - perf_counter/0
  - perf_counter/1
  - putenv/2
  - set_signal/2
  - system_time/0
  - system_time/1
  - timestamp/0
  - type/0
  - unsetenv/1
  - version/0
- pg2
  - Top of manual page
  - create/1
  - delete/1
  - get_closest_pid/1
  - get_local_members/1
  - get_members/1
  - join/2
  - leave/2
  - start/0
  - start_link/0
  - which_groups/0
- rpc
  - Top of manual page
  - abcast/2
  - abcast/3
  - async_call/4
  - block_call/4
  - block_call/5
  - call/4
  - call/5
  - cast/4
  - eval_everywhere/3
  - eval_everywhere/4
  - multi_server_call/2
  - multi_server_call/3
  - multicall/3
  - multicall/4
  - multicall/5
  - nb_yield/1
  - nb_yield/2
  - parallel_eval/1
  - pinfo/1
  - pinfo/2
  - pmap/3
  - sbcast/2
  - sbcast/3
  - server_call/4
  - yield/1
- seq_trace
  - Top of manual page
  - get_system_tracer/0
  - get_token/0
  - get_token/1
  - print/1
  - print/2
  - reset_trace/0
  - set_system_tracer/1
  - set_token/1
  - set_token/2
- user
- wrap_log_reader
  - Top of manual page
  - chunk/1
  - chunk/2
  - close/1
  - open/1
  - open/2
- zlib

# gen_tcp

### Module

gen_tcp

### Module Summary

Interface to TCP/IP sockets.

### Description

This module provides functions for communicating with sockets using the TCP/IP protocol.

The following code fragment is a simple example of a client connecting to a server at port 5678, transferring a binary, and closing the connection:

    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).

At the other end, a server is listening on port 5678, accepts the connection, and receives the binary:

    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),
        ok = gen_tcp:close(LSock),
        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.

For more examples, see section Examples.

### Data Types

option() =
{active, true | false | once | -32768..32767} |
{buffer, integer() >= 0} |
{delay_send, boolean()} |
{deliver, port | term} |
{dontroute, boolean()} |
{exit_on_close, boolean()} |
{header, integer() >= 0} |
{high_msgq_watermark, integer() >= 1} |
{high_watermark, integer() >= 0} |
{keepalive, boolean()} |
{linger, {boolean(), integer() >= 0}} |
{low_msgq_watermark, integer() >= 1} |
{low_watermark, integer() >= 0} |
{mode, list | binary} |
list |
binary |
{nodelay, boolean()} |
{packet,
0 |
1 |
2 |
4 |
raw |
sunrm |
asn1 |
cdr |
fcgi |
line |
tpkt |
http |
httph |
http_bin |
httph_bin} |
{packet_size, integer() >= 0} |
{priority, integer() >= 0} |
{raw,
Protocol :: integer() >= 0,
OptionNum :: integer() >= 0,
ValueBin :: binary()} |
{recbuf, integer() >= 0} |
{reuseaddr, boolean()} |
{send_timeout, integer() >= 0 | infinity} |
{send_timeout_close, boolean()} |
{show_econnreset, boolean()} |
{sndbuf, integer() >= 0} |
{tos, integer() >= 0} |
{tclass, integer() >= 0} |
{ttl, integer() >= 0} |
{recvtos, boolean()} |
{recvtclass, boolean()} |
{recvttl, boolean()} |
{ipv6_v6only, boolean()}
pktoptions_value() = {pktoptions, inet:ancillary_data()}

If the platform implements the IPv4 option IP_PKTOPTIONS, or the IPv6 option IPV6_PKTOPTIONS or IPV6_2292PKTOPTIONS for the socket this value is returned from inet:getopts/2 when called with the option name pktoptions.

Note

This option appears to be VERY Linux specific, and its existence in future Linux kernel versions is also worrying since the option is part of RFC 2292 which is since long (2003) obsoleted by RFC 3542 that explicitly removes this possibility to get packet information from a stream socket. For comparision: it has existed in FreeBSD but is now removed, at least since FreeBSD 10.

option_name() =
active |
buffer |
delay_send |
deliver |
dontroute |
exit_on_close |
header |
high_msgq_watermark |
high_watermark |
keepalive |
linger |
low_msgq_watermark |
low_watermark |
mode |
nodelay |
packet |
packet_size |
pktoptions |
priority |
{raw,
Protocol :: integer() >= 0,
OptionNum :: integer() >= 0,
ValueSpec ::
(ValueSize :: integer() >= 0) | (ValueBin :: binary())} |
recbuf |
reuseaddr |
send_timeout |
send_timeout_close |
show_econnreset |
sndbuf |
tos |
tclass |
ttl |
recvtos |
recvtclass |
recvttl |
pktoptions |
ipv6_v6only
connect_option() =
{ip, inet:socket_address()} |
{fd, Fd :: integer() >= 0} |
{ifaddr, inet:socket_address()} |
inet:address_family() |
{port, inet:port_number()} |
{tcp_module, module()} |
{netns, file:filename_all()} |
{bind_to_device, binary()} |
option()
listen_option() =
{ip, inet:socket_address()} |
{fd, Fd :: integer() >= 0} |
{ifaddr, inet:socket_address()} |
inet:address_family() |
{port, inet:port_number()} |
{backlog, B :: integer() >= 0} |
{tcp_module, module()} |
{netns, file:filename_all()} |
{bind_to_device, binary()} |
option()
socket()

As returned by accept/1,2 and connect/3,4.

### Exports

accept(ListenSocket) -> {ok, Socket} | {error, Reason}
accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason}

### Types

ListenSocket = socket()
Returned by listen/2.
Timeout = timeout()
Socket = socket()
Reason = closed | timeout | system_limit | inet:posix()

Accepts an incoming connection request on a listening socket. Socket must be a socket returned from listen/2. Timeout specifies a time-out value in milliseconds. Defaults to infinity.

Returns:

- {ok, Socket} if a connection is established

- {error, closed} if ListenSocket is closed

- {error, timeout} if no connection is established within the specified time

- {error, system_limit} if all available ports in the Erlang emulator are in use

- A POSIX error value if something else goes wrong, see inet(3) for possible error values

Packets can be sent to the returned socket Socket using send/2. Packets sent from the peer are delivered as messages (unless {active, false} is specified in the option list for the listening socket, in which case packets are retrieved by calling recv/2):

    {tcp, Socket, Data}

Note

The accept call does not 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.

close(Socket) -> ok

### Types

Socket = socket()

Closes a TCP socket.

Note that in most implementations of TCP, doing a close does not guarantee that any data sent is delivered to the recipient before the close is detected at the remote side. If you want to guarantee delivery of the data to the recipient there are two common ways to achieve this.

- Use gen_tcp:shutdown(Sock, write) to signal that no more data is to be sent and wait for the read side of the socket to be closed.

- Use the socket option {packet, N} (or something similar) to make it possible for the receiver to close the connection when it knowns it has received all the data.

connect(Address, Port, Options) -> {ok, Socket} | {error, Reason}
connect(Address, Port, Options, Timeout) ->
{ok, Socket} | {error, Reason}

### Types

Address = inet:socket_address() | inet:hostname()
Port = inet:port_number()
Options = [connect_option()]
Timeout = timeout()
Socket = socket()
Reason = inet:posix()

Connects to a server on TCP port Port on the host with IP address Address. Argument Address can be a hostname or an IP address.

The following options are available:

{ip, Address}

  If the host has many network interfaces, this option specifies which one to use.

{ifaddr, Address}

  Same as {ip, Address}. If the host has many network interfaces, this option specifies which one to use.

{fd, integer() >= 0}

  If a socket has somehow been connected without using gen_tcp, use this option to pass the file descriptor for it. If {ip, Address} and/or {port, port_number()} is combined with this option, the fd is bound to the specified interface and port before connecting. If these options are not specified, it is assumed that the fd is already bound appropriately.

inet

  Sets up the socket for IPv4.

inet6

  Sets up the socket for IPv6.

local

  Sets up a Unix Domain Socket. See inet:local_address()

{port, Port}

  Specifies which local port number to use.

{tcp_module, module()}

  Overrides which callback module is used. Defaults to inet_tcp for IPv4 and inet6_tcp for IPv6.

Opt

  See inet:setopts/2.

Packets can be sent to the returned socket Socket using send/2. Packets sent from the peer are delivered as messages:

    {tcp, Socket, Data}

If the socket is in {active, N} mode (see inet:setopts/2 for details) and its message counter drops to 0, the following message is delivered to indicate that the socket has transitioned to passive ({active, false}) mode:

    {tcp_passive, Socket}

If the socket is closed, the following message is delivered:

    {tcp_closed, Socket}

If an error occurs on the socket, the following message is delivered (unless {active, false} is specified in the option list for the socket, in which case packets are retrieved by calling recv/2):

    {tcp_error, Socket, Reason}

The optional Timeout parameter specifies a time-out in milliseconds. Defaults to infinity.

Note

The default values for options specified to connect can be affected by the Kernel configuration parameter inet_default_connect_options. For details, see inet(3).

controlling_process(Socket, Pid) -> ok | {error, Reason}

### Types

Socket = socket()
Pid = pid()
Reason = closed | not_owner | badarg | inet:posix()

Assigns a new controlling process Pid to Socket. The controlling process is the process that receives messages from the socket. If called by any other process than the current controlling process, {error, not_owner} is returned. If the process identified by Pid is not an existing local pid, {error, badarg} is returned. {error, badarg} may also be returned in some cases when Socket is closed during the execution of this function.

If the socket is set in active mode, this function will transfer any messages in the mailbox of the caller to the new controlling process. If any other process is interacting with the socket while the transfer is happening, the transfer may not work correctly and messages may remain in the caller's mailbox. For instance changing the sockets active mode before the transfere is complete may cause this.

listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}

### Types

Port = inet:port_number()
Options = [listen_option()]
ListenSocket = socket()
Reason = system_limit | inet:posix()

Sets up a socket to listen on port Port on the local host.

If Port == 0, the underlying OS assigns an available port number, use inet:port/1 to retrieve it.

The following options are available:

list

  Received Packet is delivered as a list.

binary

  Received Packet is delivered as a binary.

{backlog, B}

  B is an integer >= 0. The backlog value defines the maximum length that the queue of pending connections can grow to. Defaults to 5.

{ip, Address}

  If the host has many network interfaces, this option specifies which one to listen on.

{port, Port}

  Specifies which local port number to use.

{fd, Fd}

  If a socket has somehow been connected without using gen_tcp, use this option to pass the file descriptor for it.

{ifaddr, Address}

  Same as {ip, Address}. If the host has many network interfaces, this option specifies which one to use.

inet6

  Sets up the socket for IPv6.

inet

  Sets up the socket for IPv4.

{tcp_module, module()}

  Overrides which callback module is used. Defaults to inet_tcp for IPv4 and inet6_tcp for IPv6.

Opt

  See inet:setopts/2.

The returned socket ListenSocket should be used in calls to accept/1,2 to accept incoming connection requests.

Note

The default values for options specified to listen can be affected by the Kernel configuration parameter inet_default_listen_options. For details, see inet(3).

recv(Socket, Length) -> {ok, Packet} | {error, Reason}
recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason}

### Types

Socket = socket()
Length = integer() >= 0
Timeout = timeout()
Packet = string() | binary() | HttpPacket
Reason = closed | inet:posix()
HttpPacket = term()
See the description of HttpPacket in erlang:decode_packet/3 in ERTS.

Receives a packet from a socket in passive mode. A closed socket is indicated by return value {error, closed}.

Argument Length is only meaningful when the socket is in raw mode and denotes the number of bytes to read. If Length is 0, all available bytes are returned. If Length > 0, exactly Length bytes are returned, or an error; possibly discarding less than Length bytes of data when the socket is closed from the other side.

The optional Timeout parameter specifies a time-out in milliseconds. Defaults to infinity.

send(Socket, Packet) -> ok | {error, Reason}

### Types

Socket = socket()
Packet = iodata()
Reason = closed | inet:posix()

Sends a packet on a socket.

There is no send call with a time-out option, use socket option send_timeout if time-outs are desired. See section Examples.

shutdown(Socket, How) -> ok | {error, Reason}

### Types

Socket = socket()
How = read | write | read_write
Reason = inet:posix()

Closes a socket in one or two directions.

How == write means closing the socket for writing, reading from it is still possible.

If How == read or there is no outgoing data buffered in the Socket port, the socket is shut down immediately and any error encountered is returned in Reason.

If there is data buffered in the socket port, the attempt to shutdown the socket is postponed until that data is written to the kernel socket send buffer. If any errors are encountered, the socket is closed and {error, closed} is returned on the next recv/2 or send/2.

Option {exit_on_close, false} is useful if the peer has done a shutdown on the write side.

### Examples

The following example illustrates use of option {active,once} and multiple accepts by implementing a server as a number of worker processes doing accept on a single listening socket. Function start/2 takes the number of worker processes and the port number on which to listen for incoming connections. If LPort is specified as 0, an ephemeral port number is used, which is why the start function returns the actual port number allocated:

    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.

Example of a simple client:

    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.

The send call does not accept a time-out option because time-outs on send is handled through socket option send_timeout. The behavior of a send operation with no receiver is mainly defined by the underlying TCP stack and the network infrastructure. To write code that handles a hanging receiver that can eventually cause the sender to hang on a send do like the following.

Consider a process that receives data from a client process to be forwarded to a server on the network. The process is connected to the server through TCP/IP and does not get any acknowledge for each message it sends, but has to rely on the send time-out option to detect that the other end is unresponsive. Option send_timeout can be used when connecting:

    ...
    {ok,Sock} = gen_tcp:connect(HostAddress, Port,
                                [{active,false},
                                 {send_timeout, 5000},
                                 {packet,2}]),
                    loop(Sock), % See below
    ...

In the loop where requests are handled, send time-outs can now be detected:

    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.

Usually it suffices to detect time-outs on receive, as most protocols include some sort of acknowledgment from the server, but if the protocol is strictly one way, option send_timeout comes in handy.