Defold Learn logo


LuaSocket API documentation

LuaSocket is a Lua extension library that provides support for the TCP and UDP transport layers. Defold provides the "socket" namespace in runtime, which contain the core C functionality. Additional LuaSocket support modules for SMTP, HTTP, FTP etc are not part of the core included, but can be easily added to a project and used.

[icon:html5] On HTML5, the non-network helpers remain available, but TCP, UDP and socket.select() are not supported.

Note the included helper module "socket.lua" in "builtins/scripts/socket.lua". Require this module to add some additional functions and shortcuts to the namespace:

require "builtins.scripts.socket"

LuaSocket is Copyright © 2004-2007 Diego Nehab. All rights reserved. LuaSocket is free software, released under the MIT license (same license as the Lua core).

Version: alpha

TYPES
socket_client TCP client object
socket_connected Connected UDP object
socket_master TCP master object
socket_selectable Object accepted by socket.select
socket_server TCP server object
socket_unconnected Unconnected UDP object
RECORDS
socket.dns.address_info DNS address information
socket.dns.host_info DNS host information
FUNCTIONS
client:close() closes a client TCP object
client:dirty() checks the read buffer status
client:getfd() gets the socket descriptor
client:getoption() gets options for the socket
client:getpeername() gets information about a client's peer
client:getsockname() gets the local address information from client
client:getstats() gets accounting information on the socket
client:receive() receives data from a client socket
client:send() sends data through client socket
client:setfd() sets the socket descriptor
client:setoption() sets options for the socket
client:setstats() resets accounting information on the socket
client:settimeout() set the timeout values for the socket
client:shutdown() shut down socket
connected:close() closes the UDP socket
connected:getoption() gets options for the UDP socket
connected:getpeername() gets information about the UDP socket peer
connected:getsockname() gets the local address information associated to the socket
connected:receive() receives a datagram from the UDP socket
connected:send() sends a datagram through the connected UDP socket
connected:setoption() sets options for the UDP socket
connected:setpeername() remove the peer of the connected UDP socket
connected:settimeout() sets the timeout value for the UDP socket
master:bind() binds a master object to address and port on the local host
master:close() closes a master TCP object
master:connect() connects a master object to a remote host
master:dirty() checks the read buffer status
master:getfd() gets the socket descriptor
master:getsockname() gets the local address information from master
master:listen() makes the master socket listen for connections
master:setfd() sets the socket descriptor
master:settimeout() set the timeout values for the socket
server:accept() waits for a remote connection on the server object
server:close() closes a server TCP object
server:dirty() checks the read buffer status
server:getfd() gets the socket descriptor
server:getoption() gets options for the socket
server:getsockname() gets the local address information from server
server:setfd() sets the socket descriptor
server:setoption() sets options for the socket
server:settimeout() set the timeout values for the socket
socket.connect() creates a new connected TCP client object
socket.dns.getaddrinfo() resolve to IPv4 or IPv6 address
socket.dns.gethostname() gets the machine host name
socket.dns.getnameinfo() resolve to hostname (IPv4 or IPv6)
socket.dns.tohostname() resolve to host name (IPv4)
socket.dns.toip() resolve to IPv4 address
socket.gettime() gets seconds since system epoch
socket.newtry() creates a new try function
socket.protect() converts a function that throws exceptions into a safe function
socket.select() waits for a number of sockets to change status
socket.skip() drops a number of arguments and returns the remaining
socket.sleep() sleeps for a number of seconds
socket.tcp() creates a new IPv4 TCP master object
socket.tcp6() creates a new IPv6 TCP master object
socket.udp() creates a new IPv4 UDP object
socket.udp6() creates a new IPv6 UDP object
unconnected:close() closes the UDP socket
unconnected:getoption() gets options for the UDP socket
unconnected:getsockname() gets the local address information associated to the socket
unconnected:receive() receives a datagram from the UDP socket
unconnected:receivefrom() receives a datagram from the UDP socket
unconnected:sendto() sends a datagram through the UDP socket to the specified IP address and port number
unconnected:setoption() sets options for the UDP socket
unconnected:setpeername() set the peer of the unconnected UDP socket
unconnected:setsockname() binds the UDP socket to a local address
unconnected:settimeout() sets the timeout value for the UDP socket
CONSTANTS
socket._SETSIZE max numbers of sockets the select function can handle
socket._VERSION the current LuaSocket version

Types

socket_client

socket_client = userdata

A TCP socket connected to a remote endpoint. Create one with socket.connect, or by calling connect on a socket_master. Use send and receive to exchange stream data, and close when finished.

EXAMPLES

local client = assert(socket.connect("127.0.0.1", 8000))
assert(client:send("ping\n"))
client:close()

socket_connected

socket_connected = userdata

A UDP socket associated with one remote peer. Start with a socket_unconnected from socket.udp or socket.udp6, then call setpeername. Connected UDP sockets use send and receive instead of sendto and receivefrom.

EXAMPLES

local udp = assert(socket.udp())
assert(udp:setpeername("127.0.0.1", 8000))
assert(udp:send("ping"))

socket_master

socket_master = userdata

A newly created TCP socket that is not yet connected or listening. Obtain one from socket.tcp or socket.tcp6. Calling connect transforms it into a socket_client; calling bind followed by listen transforms it into a socket_server.

EXAMPLES

local tcp = assert(socket.tcp())
assert(tcp:bind("*", 8000))
assert(tcp:listen(32))

socket_selectable

socket_selectable = socket_master | socket_client | socket_server | socket_connected | socket_unconnected | { getfd:fun(self:any):integer, dirty:fun(self:any):boolean }

In addition to LuaSocket TCP and UDP objects, socket.select() accepts any object that implements compatible getfd and dirty methods.

EXAMPLES

Test whether a client can be read without blocking:
local client = assert(socket.connect("127.0.0.1", 8000))
local readable = socket.select({ client }, {}, 0)
if #readable > 0 then
    local data = client:receive()
end

socket_server

socket_server = userdata

A TCP socket listening for incoming connections. Create one by binding a socket_master and calling its listen method. Calling accept returns a socket_client for an incoming connection.

EXAMPLES

local server = assert(socket.tcp())
assert(server:bind("*", 8000))
assert(server:listen(32))
local client = assert(server:accept())

socket_unconnected

socket_unconnected = userdata

A UDP socket without a fixed remote peer, created by socket.udp or socket.udp6. Use sendto and receivefrom with explicit addresses, or call setpeername to transform it into a socket_connected.

EXAMPLES

local udp = assert(socket.udp())
assert(udp:sendto("ping", "127.0.0.1", 8000))

Records

socket.dns.address_info

DNS address information

FIELDS

family string "inet" for IPv4 or "inet6" for IPv6
addr string resolved IP address

socket.dns.host_info

DNS host information

FIELDS

name string canonical host name
alias string[] host aliases
ip string[] resolved IPv4 addresses

Functions

client:close()

client:close()→success:number

Closes the TCP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed socket. It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.

PARAMETERS

None

RETURNS

success number
the value 1.

client:dirty()

client:dirty()→status:boolean

Check the read buffer status. This is an internal method, any use is unlikely to be portable.

PARAMETERS

None

RETURNS

status boolean
true if there is any data in the read buffer, false otherwise.

client:getfd()

client:getfd()→handle:number

Returns the underlying socket descriptor or handle associated to the object. This is an internal method, any use is unlikely to be portable.

PARAMETERS

None

RETURNS

handle number
the descriptor or handle. In case the object has been closed, the return will be -1.

client:getoption()

client:getoption(option:string)→(value:any|nil, error:string|nil)

Gets options for the TCP object. See client:setoption for description of the option names and values.

PARAMETERS

option string
the name of the option to get:
  • "keepalive"
  • "linger"
  • "reuseaddr"
  • "tcp-nodelay"

RETURNS

value any
nil
the option value, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

client:getpeername()

client:getpeername()→(address:string|nil, port_or_error:integer|string, family:string|nil)

Returns information about the remote side of a connected client object. It makes no sense to call this method on server objects.

PARAMETERS

None

RETURNS

address string
nil
the IP address of the peer, or nil in case of error.
port_or_error integer
string
the peer port number, or the error message in case of error.
family string
nil
the socket family ("inet" or "inet6"), or nil in case of error.

client:getsockname()

client:getsockname()→(address:string|nil, port_or_error:string, family:string|nil)

Returns the local address information associated to the object.

PARAMETERS

None

RETURNS

address string
nil
the local IP address, or nil in case of error.
port_or_error string
the local port, or the error message in case of error.
family string
nil
the socket family ("inet" or "inet6"), or nil in case of error.

client:getstats()

client:getstats()→(received:number, sent:number, age:number)

Returns accounting information on the socket, useful for throttling of bandwidth.

PARAMETERS

None

RETURNS

received number
the number of bytes received.
sent number
the number of bytes sent.
age number
the age of the socket object in seconds.

client:receive()

client:receive([pattern:string|number], [prefix:string])→(data:string|nil, error:string|nil, partial:string|nil)

Reads data from a client object, according to the specified read pattern. Patterns follow the Lua file I/O format, and the difference in performance between patterns is negligible.

PARAMETERS

[pattern] string
number
the read pattern that can be any of the following:
"*a"
reads from the socket until the connection is closed. No end-of-line translation is performed;
"*l"
reads a line of text from the socket. The line is terminated by a LF character (ASCII 10), optionally preceded by a CR character (ASCII 13). The CR and LF characters are not included in the returned line. In fact, all CR characters are ignored by the pattern. This is the default pattern;
number
causes the method to read a specified number of bytes from the socket.
[prefix] string
an optional string to be concatenated to the beginning of any received data before return.

RETURNS

data string
nil
the received pattern, or nil in case of error.
error string
nil
the error message, or nil if no error occurred. The error message can be the string "closed" in case the connection was closed before the transmission was completed or the string "timeout" in case there was a timeout during the operation.
partial string
nil
a (possibly empty) string containing the partial that was received, or nil if no error occurred.

client:send()

client:send(data:string, [i:number], [j:number])→(index:number|nil, error:string|nil, lastindex:number|nil)

Sends data through client object. The optional arguments i and j work exactly like the standard string.sub Lua function to allow the selection of a substring to be sent. Output is not buffered. For small strings, it is always better to concatenate them in Lua (with the .. operator) and send the result in one call instead of calling the method several times.

PARAMETERS

data string
the string to be sent.
[i] number
optional starting index of the string.
[j] number
optional end index of string.

RETURNS

index number
nil
the index of the last byte within [i, j] that has been sent, or nil in case of error. Notice that, if i is 1 or absent, this is effectively the total number of bytes sent.
error string
nil
the error message, or nil if no error occurred. The error message can be "closed" in case the connection was closed before the transmission was completed or the string "timeout" in case there was a timeout during the operation.
lastindex number
nil
in case of error, the index of the last byte within [i, j] that has been sent. You might want to try again from the byte following that. nil if no error occurred.

client:setfd()

client:setfd(handle:number)

Sets the underling socket descriptor or handle associated to the object. The current one is simply replaced, not closed, and no other change to the object state is made

PARAMETERS

handle number
the descriptor or handle to set.

client:setoption()

client:setoption(option:string, [value:any])→(status:number|nil, error:string|nil)

Sets options for the TCP object. Options are only needed by low-level or time-critical applications. You should only modify an option if you are sure you need it.

PARAMETERS

option string
the name of the option to set. The value is provided in the value parameter:
"keepalive"
Setting this option to true enables the periodic transmission of messages on a connected socket. Should the connected party fail to respond to these messages, the connection is considered broken and processes using the socket are notified;
"linger"
Controls the action taken when unsent data are queued on a socket and a close is performed. The value is a table with the following keys:
If the 'on' field is set to true, the system will block the process on the close attempt until it is able to transmit the data or until timeout has passed. If 'on' is false and a close is issued, the system will process the close in a manner that allows the process to continue as quickly as possible. It is not advised to set this to anything other than zero;
"reuseaddr"
Setting this option indicates that the rules used in validating addresses supplied in a call to bind should allow reuse of local addresses;
"tcp-nodelay"
Setting this option to true disables the Nagle's algorithm for the connection;
"ipv6-v6only"
Setting this option to true restricts an inet6 socket to sending and receiving only IPv6 packets.
[value] any
the value to set for the specified option.

RETURNS

status number
nil
the value 1, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

client:setstats()

client:setstats([received:number|nil], [sent:number|nil], [age:number|nil])→success:number

Resets accounting information on the socket, useful for throttling of bandwidth.

PARAMETERS

[received] number
nil
the new number of bytes received, or nil to preserve it.
[sent] number
nil
the new number of bytes sent, or nil to preserve it.
[age] number
nil
the new age in seconds, or nil to preserve it.

RETURNS

success number
the value 1.

client:settimeout()

client:settimeout([value:number|nil], [mode:string])→success:number

Changes the timeout values for the object. By default, all I/O operations are blocking. That is, any call to the methods send, receive, and accept will block indefinitely, until the operation completes. The settimeout method defines a limit on the amount of time the I/O methods can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code. There are two timeout modes and both can be used together for fine tuning. Although timeout values have millisecond precision in LuaSocket, large blocks can cause I/O functions not to respect timeout values due to the time the library takes to transfer blocks to and from the OS and to and from the Lua interpreter. Also, function that accept host names and perform automatic name resolution might be blocked by the resolver for longer than the specified timeout value.

PARAMETERS

[value] number
nil
the amount of time to wait, in seconds. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.
[mode] string
optional timeout mode to set:
"b"
block timeout. Specifies the upper limit on the amount of time LuaSocket can be blocked by the operating system while waiting for completion of any single I/O operation. This is the default mode;
"t"
total timeout. Specifies the upper limit on the amount of time LuaSocket can block a Lua script before returning from a call.

RETURNS

success number
the value 1.

client:shutdown()

client:shutdown(mode:string)→status:number

Shuts down part of a full-duplex connection.

PARAMETERS

mode string
which way of the connection should be shut down:
"both"
disallow further sends and receives on the object. This is the default mode;
"send"
disallow further sends on the object;
"receive"
disallow further receives on the object.

RETURNS

status number
the value 1.

connected:close()

connected:close()→success:number

Closes a UDP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed socket. It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.

PARAMETERS

None

RETURNS

success number
the value 1.

connected:getoption()

connected:getoption(option:string)→(value:any|nil, error:string|nil)

Gets an option value from the UDP object. See connected:setoption for description of the option names and values.

PARAMETERS

option string
the name of the option to get:
  • "dontroute"
  • "broadcast"
  • "reuseaddr"
  • "reuseport"
  • "ip-multicast-loop"
  • "ipv6-v6only"
  • "ip-multicast-if"
  • "ip-multicast-ttl"
  • "ip-add-membership"
  • "ip-drop-membership"

RETURNS

value any
nil
the option value, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

connected:getpeername()

connected:getpeername()→(address:string|nil, port_or_error:integer|string, family:string|nil)

Retrieves information about the peer associated with a connected UDP object. It makes no sense to call this method on unconnected objects.

PARAMETERS

None

RETURNS

address string
nil
the IP address of the peer, or nil in case of error.
port_or_error integer
string
the peer port number, or the error message in case of error.
family string
nil
the socket family ("inet" or "inet6"), or nil in case of error.

connected:getsockname()

connected:getsockname()→(address:string|nil, port_or_error:string, family:string|nil)

Returns the local address information associated to the object. UDP sockets are not bound to any address until the setsockname or the sendto method is called for the first time (in which case it is bound to an ephemeral port and the wild-card address).

PARAMETERS

None

RETURNS

address string
nil
the local IP address, or nil in case of error.
port_or_error string
the local port, or the error message in case of error.
family string
nil
the socket family ("inet" or "inet6"), or nil in case of error.

connected:receive()

connected:receive([size:number])→(datagram:string|nil, error:string|nil)

Receives a datagram from the UDP object. If the UDP object is connected, only datagrams coming from the peer are accepted. Otherwise, the returned datagram can come from any host.

PARAMETERS

[size] number
optional maximum size of the datagram to be retrieved. If there are more than size bytes available in the datagram, the excess bytes are discarded. If there are less then size bytes available in the current datagram, the available bytes are returned. If size is omitted, the maximum datagram size is used (which is currently limited by the implementation to 8192 bytes).

RETURNS

datagram string
nil
the received datagram, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

connected:send()

connected:send(datagram:string)→(success:number|nil, error:string|nil)

Sends a datagram to the UDP peer of a connected object. In UDP, the send method never blocks and the only way it can fail is if the underlying transport layer refuses to send a message to the specified address (i.e. no interface accepts the address).

PARAMETERS

datagram string
a string with the datagram contents. The maximum datagram size for UDP is 64K minus IP layer overhead. However datagrams larger than the link layer packet size will be fragmented, which may deteriorate performance and/or reliability.

RETURNS

success number
nil
the value 1 on success, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

connected:setoption()

connected:setoption(option:string, [value:any])→(status:number|nil, error:string|nil)

Sets options for the UDP object. Options are only needed by low-level or time-critical applications. You should only modify an option if you are sure you need it.

PARAMETERS

option string
the name of the option to set. The value is provided in the value parameter:
"dontroute"
Indicates that outgoing messages should bypass the standard routing facilities. Receives a boolean value;
"broadcast"
Requests permission to send broadcast datagrams on the socket. Receives a boolean value;
"reuseaddr"
Indicates that the rules used in validating addresses supplied in a bind call should allow reuse of local addresses. Receives a boolean value;
"reuseport"
Allows completely duplicate bindings by multiple processes if they all set "reuseport" before binding the port. Receives a boolean value;
"ip-multicast-loop"
Specifies whether or not a copy of an outgoing multicast datagram is delivered to the sending host as long as it is a member of the multicast group. Receives a boolean value;
"ipv6-v6only"
Specifies whether to restrict inet6 sockets to sending and receiving only IPv6 packets. Receive a boolean value;
"ip-multicast-if"
Sets the interface over which outgoing multicast datagrams are sent. Receives an IP address;
"ip-multicast-ttl"
Sets the Time To Live in the IP header for outgoing multicast datagrams. Receives a number;
"ip-add-membership": Joins the multicast group specified. Receives a table with fields:
  • string multiaddr (IP address)
  • string interface (IP address)
"'ip-drop-membership"`
Leaves the multicast group specified. Receives a table with fields:
  • string multiaddr (IP address)
  • string interface (IP address)
[value] any
the value to set for the specified option.

RETURNS

status number
nil
the value 1, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

connected:setpeername()

connected:setpeername(address:string)→(success:number|nil, error:string|nil)

Changes the peer of a UDP object. This method turns an unconnected UDP object into a connected UDP object or vice versa. For connected objects, outgoing datagrams will be sent to the specified peer, and datagrams received from other peers will be discarded by the OS. Connected UDP objects must use the send and receive methods instead of sendto and receivefrom. Since the address of the peer does not have to be passed to and from the OS, the use of connected UDP objects is recommended when the same peer is used for several transmissions and can result in up to 30% performance gains.

PARAMETERS

address string
must be "*". The peer association is removed and the object becomes an unconnected object again.

RETURNS

success number
nil
the value 1 on success, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

connected:settimeout()

connected:settimeout([value:number|nil])→success:number

Changes the timeout values for the object. By default, the receive and receivefrom operations are blocking. That is, any call to the methods will block indefinitely, until data arrives. The settimeout function defines a limit on the amount of time the functions can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code. In UDP, the send and sendto methods never block (the datagram is just passed to the OS and the call returns immediately). Therefore, the settimeout method has no effect on them.

PARAMETERS

[value] number
nil
the amount of time to wait, in seconds. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.

RETURNS

success number
the value 1.

master:bind()

master:bind(address:string, port:number)→(status:number|nil, error:string|nil)

Binds a master object to address and port on the local host.

PARAMETERS

address string
an IP address or a host name. If address is "*", the system binds to all local interfaces using the INADDR_ANY constant.
port number
the port to commect to, in the range [0..64K). If port is 0, the system automatically chooses an ephemeral port.

RETURNS

status number
nil
the value 1, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

master:close()

master:close()→success:number

Closes the TCP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed socket. It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.

PARAMETERS

None

RETURNS

success number
the value 1.

master:connect()

master:connect(address:string, port:number)→(status:number|nil, error:string|nil)

Attempts to connect a master object to a remote host, transforming it into a client object. Client objects support methods send, receive, getsockname, getpeername, settimeout, and close. Note that the function socket.connect is available and is a shortcut for the creation of client sockets.

PARAMETERS

address string
an IP address or a host name. If address is "*", the system binds to all local interfaces using the INADDR_ANY constant.
port number
the port to commect to, in the range [0..64K). If port is 0, the system automatically chooses an ephemeral port.

RETURNS

status number
nil
the value 1, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

master:dirty()

master:dirty()→status:boolean

Check the read buffer status. This is an internal method, any use is unlikely to be portable.

PARAMETERS

None

RETURNS

status boolean
true if there is any data in the read buffer, false otherwise.

master:getfd()

master:getfd()→handle:number

Returns the underlying socket descriptor or handle associated to the object. This is an internal method, any use is unlikely to be portable.

PARAMETERS

None

RETURNS

handle number
the descriptor or handle. In case the object has been closed, the return will be -1.

master:getsockname()

master:getsockname()→(address:string|nil, port_or_error:string, family:string|nil)

Returns the local address information associated to the object.

PARAMETERS

None

RETURNS

address string
nil
the local IP address, or nil in case of error.
port_or_error string
the local port, or the error message in case of error.
family string
nil
the socket family ("inet" or "inet6"), or nil in case of error.

master:listen()

master:listen(backlog:number)→(status:number|nil, error:string|nil)

Specifies the socket is willing to receive connections, transforming the object into a server object. Server objects support the accept, getsockname, setoption, settimeout, and close methods.

PARAMETERS

backlog number
the number of client connections that can be queued waiting for service. If the queue is full and another client attempts connection, the connection is refused.

RETURNS

status number
nil
the value 1, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

master:setfd()

master:setfd(handle:number)

Sets the underling socket descriptor or handle associated to the object. The current one is simply replaced, not closed, and no other change to the object state is made

PARAMETERS

handle number
the descriptor or handle to set.

master:settimeout()

master:settimeout([value:number|nil], [mode:string])→success:number

Changes the timeout values for the object. By default, all I/O operations are blocking. That is, any call to the methods send, receive, and accept will block indefinitely, until the operation completes. The settimeout method defines a limit on the amount of time the I/O methods can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code. There are two timeout modes and both can be used together for fine tuning. Although timeout values have millisecond precision in LuaSocket, large blocks can cause I/O functions not to respect timeout values due to the time the library takes to transfer blocks to and from the OS and to and from the Lua interpreter. Also, function that accept host names and perform automatic name resolution might be blocked by the resolver for longer than the specified timeout value.

PARAMETERS

[value] number
nil
the amount of time to wait, in seconds. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.
[mode] string
optional timeout mode to set:
"b"
block timeout. Specifies the upper limit on the amount of time LuaSocket can be blocked by the operating system while waiting for completion of any single I/O operation. This is the default mode;
"t"
total timeout. Specifies the upper limit on the amount of time LuaSocket can block a Lua script before returning from a call.

RETURNS

success number
the value 1.

server:accept()

server:accept()→(tcp_client:socket_client|nil, error:string|nil)

Waits for a remote connection on the server object and returns a client object representing that connection. Calling socket.select with a server object in the recvt parameter before a call to accept does not guarantee accept will return immediately. Use the settimeout method or accept might block until another client shows up.

PARAMETERS

None

RETURNS

tcp_client socket_client
nil
if a connection is successfully initiated, a client object is returned, or nil in case of error.
error string
nil
the error message, or nil if no error occurred. The error is "timeout" if a timeout condition is met.

server:close()

server:close()→success:number

Closes the TCP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed socket. It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.

PARAMETERS

None

RETURNS

success number
the value 1.

server:dirty()

server:dirty()→status:boolean

Check the read buffer status. This is an internal method, any use is unlikely to be portable.

PARAMETERS

None

RETURNS

status boolean
true if there is any data in the read buffer, false otherwise.

server:getfd()

server:getfd()→handle:number

Returns the underlying socket descriptor or handle associated to the object. This is an internal method, any use is unlikely to be portable.

PARAMETERS

None

RETURNS

handle number
the descriptor or handle. In case the object has been closed, the return will be -1.

server:getoption()

server:getoption(option:string)→(value:any|nil, error:string|nil)

Gets options for the TCP object. See server:setoption for description of the option names and values.

PARAMETERS

option string
the name of the option to get:
  • "keepalive"
  • "linger"
  • "reuseaddr"
  • "tcp-nodelay"

RETURNS

value any
nil
the option value, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

server:getsockname()

server:getsockname()→(address:string|nil, port_or_error:string, family:string|nil)

Returns the local address information associated to the object.

PARAMETERS

None

RETURNS

address string
nil
the local IP address, or nil in case of error.
port_or_error string
the local port, or the error message in case of error.
family string
nil
the socket family ("inet" or "inet6"), or nil in case of error.

server:setfd()

server:setfd(handle:number)

Sets the underling socket descriptor or handle associated to the object. The current one is simply replaced, not closed, and no other change to the object state is made

PARAMETERS

handle number
the descriptor or handle to set.

server:setoption()

server:setoption(option:string, [value:any])→(status:number|nil, error:string|nil)

Sets options for the TCP object. Options are only needed by low-level or time-critical applications. You should only modify an option if you are sure you need it.

PARAMETERS

option string
the name of the option to set. The value is provided in the value parameter:
"keepalive"
Setting this option to true enables the periodic transmission of messages on a connected socket. Should the connected party fail to respond to these messages, the connection is considered broken and processes using the socket are notified;
"linger"
Controls the action taken when unsent data are queued on a socket and a close is performed. The value is a table with the following keys:
If the 'on' field is set to true, the system will block the process on the close attempt until it is able to transmit the data or until timeout has passed. If 'on' is false and a close is issued, the system will process the close in a manner that allows the process to continue as quickly as possible. It is not advised to set this to anything other than zero;
"reuseaddr"
Setting this option indicates that the rules used in validating addresses supplied in a call to bind should allow reuse of local addresses;
"tcp-nodelay"
Setting this option to true disables the Nagle's algorithm for the connection;
"ipv6-v6only"
Setting this option to true restricts an inet6 socket to sending and receiving only IPv6 packets.
[value] any
the value to set for the specified option.

RETURNS

status number
nil
the value 1, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

server:settimeout()

server:settimeout([value:number|nil], [mode:string])→success:number

Changes the timeout values for the object. By default, all I/O operations are blocking. That is, any call to the methods send, receive, and accept will block indefinitely, until the operation completes. The settimeout method defines a limit on the amount of time the I/O methods can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code. There are two timeout modes and both can be used together for fine tuning. Although timeout values have millisecond precision in LuaSocket, large blocks can cause I/O functions not to respect timeout values due to the time the library takes to transfer blocks to and from the OS and to and from the Lua interpreter. Also, function that accept host names and perform automatic name resolution might be blocked by the resolver for longer than the specified timeout value.

PARAMETERS

[value] number
nil
the amount of time to wait, in seconds. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.
[mode] string
optional timeout mode to set:
"b"
block timeout. Specifies the upper limit on the amount of time LuaSocket can be blocked by the operating system while waiting for completion of any single I/O operation. This is the default mode;
"t"
total timeout. Specifies the upper limit on the amount of time LuaSocket can block a Lua script before returning from a call.

RETURNS

success number
the value 1.

socket.connect()

socket.connect(address:string, port:number, [locaddr:string], [locport:number], [family:string])→(tcp_client:socket_client|nil, error:string|nil)

This function is a shortcut that creates and returns a TCP client object connected to a remote address at a given port. Optionally, the user can also specify the local address and port to bind (locaddr and locport), or restrict the socket family to "inet" or "inet6". Without specifying family to connect, whether a tcp or tcp6 connection is created depends on your system configuration.

PARAMETERS

address string
the address to connect to.
port number
the port to connect to.
[locaddr] string
optional local address to bind to.
[locport] number
optional local port to bind to.
[family] string
optional socket family to use, "inet" or "inet6".

RETURNS

tcp_client socket_client
nil
a new IPv6 TCP client object, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

socket.dns.getaddrinfo()

socket.dns.getaddrinfo(address:string)→(resolved:socket.dns.address_info[]|nil, error:string|nil)

This function converts a host name to IPv4 or IPv6 address. The supplied address can be an IPv4 or IPv6 address or host name. In case of error, the function returns nil followed by an error message.

PARAMETERS

address string
a hostname or an IPv4 or IPv6 address.

RETURNS

resolved socket.dns.address_info[]
nil
resolver information, or nil on error
error string
nil
the error message, or nil if no error occurred.

socket.dns.gethostname()

socket.dns.gethostname()→hostname:string

Returns the standard host name for the machine as a string.

PARAMETERS

None

RETURNS

hostname string
the host name for the machine.

socket.dns.getnameinfo()

socket.dns.getnameinfo(address:string)→(resolved:string[]|nil, error:string|nil)

This function converts an address to host name. The supplied address can be an IPv4 or IPv6 address or host name. The function returns a table with all information returned by the resolver:

{
  [1] = host-name-1,
  ...
  [n] = host-name-n,
}

PARAMETERS

address string
a hostname or an IPv4 or IPv6 address.

RETURNS

resolved string[]
nil
a table with all information returned by the resolver, or if an error occurs, nil.
error string
nil
the error message, or nil if no error occurred.

socket.dns.tohostname()

socket.dns.tohostname(address:string)→(hostname:string|nil, resolved:socket.dns.host_info|string)

This function converts from an IPv4 address to host name. The address can be an IPv4 address or a host name.

PARAMETERS

address string
an IPv4 address or host name.

RETURNS

hostname string
nil
the canonic host name of the given address, or nil in case of an error.
resolved socket.dns.host_info
string
resolver information, or an error message string

socket.dns.toip()

socket.dns.toip(address:string)→(ip_address:string|nil, resolved:socket.dns.host_info|string)

This function converts a host name to IPv4 address. The address can be an IP address or a host name.

PARAMETERS

address string
a hostname or an IP address.

RETURNS

ip_address string
nil
the first IP address found for the hostname, or nil in case of an error.
resolved socket.dns.host_info
string
resolver information, or an error message string

socket.gettime()

socket.gettime()→seconds:number

Returns the time in seconds, relative to the system epoch (Unix epoch time since January 1, 1970 (UTC) or Windows file time since January 1, 1601 (UTC)). You should use the values returned by this function for relative measurements only.

PARAMETERS

None

RETURNS

seconds number
the number of seconds elapsed.

EXAMPLES

How to use the gettime() function to measure running time:
t = socket.gettime()
-- do stuff
print(socket.gettime() - t .. " seconds elapsed")

socket.newtry()

socket.newtry(finalizer:fun())→try:fun(...:any):any

This function creates and returns a clean try function that allows for cleanup before the exception is raised. The finalizer function will be called in protected mode (see protect).

PARAMETERS

finalizer function()
a function that will be called before the try throws the exception.

RETURNS

try function( ...:any):any
the customized try function.

EXAMPLES

Perform operations on an open socket c:
-- create a try function that closes 'c' on error
local try = socket.newtry(function() c:close() end)
-- do everything reassured c will be closed
try(c:send("hello there?\r\n"))
local answer = try(c:receive())
...
try(c:send("good bye\r\n"))
c:close()

socket.protect()

socket.protect(func:fun(...:any):any)→safe_func:fun(...:any):any

Converts a function that throws exceptions into a safe function. This function only catches exceptions thrown by try functions. It does not catch normal Lua errors. Beware that if your function performs some illegal operation that raises an error, the protected function will catch the error and return it as a string. This is because try functions uses errors as the mechanism to throw exceptions.

PARAMETERS

func function( ...:any):any
a function that calls a try function (or assert, or error) to throw exceptions.

RETURNS

safe_func function( ...:any):any
an equivalent function that instead of throwing exceptions, returns nil followed by an error message.

EXAMPLES

local dostuff = socket.protect(function()
    local try = socket.newtry()
    local c = try(socket.connect("myserver.com", 80))
    try = socket.newtry(function() c:close() end)
    try(c:send("hello?\r\n"))
    local answer = try(c:receive())
    c:close()
end)

local n, error = dostuff()

socket.select()

socket.select(recvt:socket_selectable[], sendt:socket_selectable[], [timeout:number])→(sockets_r:table<integer|socket_selectable, socket_selectable|integer>, sockets_w:table<integer|socket_selectable, socket_selectable|integer>, error:string|nil)

The function returns a list with the sockets ready for reading, a list with the sockets ready for writing and an error message. The error message is "timeout" if a timeout condition was met and nil otherwise. The returned tables are doubly keyed both by integers and also by the sockets themselves, to simplify the test if a specific socket has changed status. Recvt and sendt parameters can be empty tables or nil. Non-socket values (or values with non-numeric indices) in these arrays will be silently ignored. The returned tables are doubly keyed both by integers and also by the sockets themselves, to simplify the test if a specific socket has changed status. This function can monitor a limited number of sockets, as defined by the constant socket._SETSIZE. This number may be as high as 1024 or as low as 64 by default, depending on the system. It is usually possible to change this at compile time. Invoking select with a larger number of sockets will raise an error. A known bug in WinSock causes select to fail on non-blocking TCP sockets. The function may return a socket as writable even though the socket is not ready for sending. Calling select with a server socket in the receive parameter before a call to accept does not guarantee accept will return immediately. Use the settimeout method or accept might block forever. If you close a socket and pass it to select, it will be ignored. (Using select with non-socket objects: Any object that implements getfd and dirty can be used with select, allowing objects from other libraries to be used within a socket.select driven loop.)

PARAMETERS

recvt socket_selectable[]
array with the sockets or compatible objects to test for characters available for reading.
sendt socket_selectable[]
array with sockets or compatible objects that are watched to see if it is OK to immediately write on them.
[timeout] number
the maximum amount of time (in seconds) to wait for a change in status. Nil, negative or omitted timeout value allows the function to block indefinitely.

RETURNS

sockets_r table<integer|socket_selectable, socket_selectable|integer>
sockets ready for reading, keyed both by array index and by socket.
sockets_w table<integer|socket_selectable, socket_selectable|integer>
sockets ready for writing, keyed both by array index and by socket.
error string
nil
an error message. "timeout" if a timeout condition was met, otherwise nil.

socket.skip()

socket.skip(d:integer, ...:any)→...:any

This function drops a number of arguments and returns the remaining. It is useful to avoid creation of dummy variables: D is the number of arguments to drop. Ret1 to retN are the arguments. The function returns retD+1 to retN.

PARAMETERS

d integer
the number of arguments to drop.
... any
the values from which to drop arguments.

RETURNS

... any
the remaining values after the first d values are dropped.

EXAMPLES

Instead of doing the following with dummy variables:
-- get the status code and separator from SMTP server reply
local dummy1, dummy2, code, sep = string.find(line, "^(%d%d%d)(.?)")
You can skip a number of variables:
-- get the status code and separator from SMTP server reply
local code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))

socket.sleep()

socket.sleep(time:number)

Freezes the program execution during a given amount of time.

PARAMETERS

time number
the number of seconds to sleep for.

socket.tcp()

socket.tcp()→(tcp_master:socket_master|nil, error:string|nil)

Creates and returns an IPv4 TCP master object. A master object can be transformed into a server object with the method listen (after a call to bind) or into a client object with the method connect. The only other method supported by a master object is the close method.

PARAMETERS

None

RETURNS

tcp_master socket_master
nil
a new IPv4 TCP master object, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

socket.tcp6()

socket.tcp6()→(tcp_master:socket_master|nil, error:string|nil)

Creates and returns an IPv6 TCP master object. A master object can be transformed into a server object with the method listen (after a call to bind) or into a client object with the method connect. The only other method supported by a master object is the close method. Note: The TCP object returned will have the option "ipv6-v6only" set to true.

PARAMETERS

None

RETURNS

tcp_master socket_master
nil
a new IPv6 TCP master object, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

socket.udp()

socket.udp()→(udp_unconnected:socket_unconnected|nil, error:string|nil)

Creates and returns an unconnected IPv4 UDP object. Unconnected objects support the sendto, receive, receivefrom, getoption, getsockname, setoption, settimeout, setpeername, setsockname, and close methods. The setpeername method is used to connect the object.

PARAMETERS

None

RETURNS

udp_unconnected socket_unconnected
nil
a new unconnected IPv4 UDP object, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

socket.udp6()

socket.udp6()→(udp_unconnected:socket_unconnected|nil, error:string|nil)

Creates and returns an unconnected IPv6 UDP object. Unconnected objects support the sendto, receive, receivefrom, getoption, getsockname, setoption, settimeout, setpeername, setsockname, and close methods. The setpeername method is used to connect the object. Note: The UDP object returned will have the option "ipv6-v6only" set to true.

PARAMETERS

None

RETURNS

udp_unconnected socket_unconnected
nil
a new unconnected IPv6 UDP object, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

unconnected:close()

unconnected:close()→success:number

Closes a UDP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed socket. It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.

PARAMETERS

None

RETURNS

success number
the value 1.

unconnected:getoption()

unconnected:getoption(option:string)→(value:any|nil, error:string|nil)

Gets an option value from the UDP object. See unconnected:setoption for description of the option names and values.

PARAMETERS

option string
the name of the option to get:
  • "dontroute"
  • "broadcast"
  • "reuseaddr"
  • "reuseport"
  • "ip-multicast-loop"
  • "ipv6-v6only"
  • "ip-multicast-if"
  • "ip-multicast-ttl"
  • "ip-add-membership"
  • "ip-drop-membership"

RETURNS

value any
nil
the option value, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

unconnected:getsockname()

unconnected:getsockname()→(address:string|nil, port_or_error:string, family:string|nil)

Returns the local address information associated to the object. UDP sockets are not bound to any address until the setsockname or the sendto method is called for the first time (in which case it is bound to an ephemeral port and the wild-card address).

PARAMETERS

None

RETURNS

address string
nil
the local IP address, or nil in case of error.
port_or_error string
the local port, or the error message in case of error.
family string
nil
the socket family ("inet" or "inet6"), or nil in case of error.

unconnected:receive()

unconnected:receive([size:number])→(datagram:string|nil, error:string|nil)

Receives a datagram from the UDP object. If the UDP object is connected, only datagrams coming from the peer are accepted. Otherwise, the returned datagram can come from any host.

PARAMETERS

[size] number
optional maximum size of the datagram to be retrieved. If there are more than size bytes available in the datagram, the excess bytes are discarded. If there are less then size bytes available in the current datagram, the available bytes are returned. If size is omitted, the maximum datagram size is used (which is currently limited by the implementation to 8192 bytes).

RETURNS

datagram string
nil
the received datagram, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

unconnected:receivefrom()

unconnected:receivefrom([size:number])→(datagram:string|nil, ip_or_error:string, port:number|nil)

Works exactly as the receive method, except it returns the IP address and port as extra return values (and is therefore slightly less efficient).

PARAMETERS

[size] number
optional maximum size of the datagram to be retrieved.

RETURNS

datagram string
nil
the received datagram, or nil in case of error.
ip_or_error string
the IP address, or the error message in case of error.
port number
nil
the port number, or nil in case of error.

unconnected:sendto()

unconnected:sendto(datagram:string, ip:string, port:number)→(success:number|nil, error:string|nil)

Sends a datagram to the specified IP address and port number. In UDP, the send method never blocks and the only way it can fail is if the underlying transport layer refuses to send a message to the specified address (i.e. no interface accepts the address).

PARAMETERS

datagram string
a string with the datagram contents. The maximum datagram size for UDP is 64K minus IP layer overhead. However datagrams larger than the link layer packet size will be fragmented, which may deteriorate performance and/or reliability.
ip string
the IP address of the recipient. Host names are not allowed for performance reasons.
port number
the port number at the recipient.

RETURNS

success number
nil
the value 1 on success, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

unconnected:setoption()

unconnected:setoption(option:string, [value:any])→(status:number|nil, error:string|nil)

Sets options for the UDP object. Options are only needed by low-level or time-critical applications. You should only modify an option if you are sure you need it.

PARAMETERS

option string
the name of the option to set. The value is provided in the value parameter:
"dontroute"
Indicates that outgoing messages should bypass the standard routing facilities. Receives a boolean value;
"broadcast"
Requests permission to send broadcast datagrams on the socket. Receives a boolean value;
"reuseaddr"
Indicates that the rules used in validating addresses supplied in a bind call should allow reuse of local addresses. Receives a boolean value;
"reuseport"
Allows completely duplicate bindings by multiple processes if they all set "reuseport" before binding the port. Receives a boolean value;
"ip-multicast-loop"
Specifies whether or not a copy of an outgoing multicast datagram is delivered to the sending host as long as it is a member of the multicast group. Receives a boolean value;
"ipv6-v6only"
Specifies whether to restrict inet6 sockets to sending and receiving only IPv6 packets. Receive a boolean value;
"ip-multicast-if"
Sets the interface over which outgoing multicast datagrams are sent. Receives an IP address;
"ip-multicast-ttl"
Sets the Time To Live in the IP header for outgoing multicast datagrams. Receives a number;
"ip-add-membership": Joins the multicast group specified. Receives a table with fields:
  • string multiaddr (IP address)
  • string interface (IP address)
"'ip-drop-membership"`
Leaves the multicast group specified. Receives a table with fields:
  • string multiaddr (IP address)
  • string interface (IP address)
[value] any
the value to set for the specified option.

RETURNS

status number
nil
the value 1, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

unconnected:setpeername()

unconnected:setpeername(address:string, port:number)→(success:number|nil, error:string|nil)

Changes the peer of a UDP object. This method turns an unconnected UDP object into a connected UDP object or vice versa. For connected objects, outgoing datagrams will be sent to the specified peer, and datagrams received from other peers will be discarded by the OS. Connected UDP objects must use the send and receive methods instead of sendto and receivefrom. Since the address of the peer does not have to be passed to and from the OS, the use of connected UDP objects is recommended when the same peer is used for several transmissions and can result in up to 30% performance gains.

PARAMETERS

address string
an IP address or a host name.
port number
the port number.

RETURNS

success number
nil
the value 1 on success, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

unconnected:setsockname()

unconnected:setsockname(address:string, port:number)→(success:number|nil, error:string|nil)

Binds the UDP object to a local address. This method can only be called before any datagram is sent through the UDP object, and only once. Otherwise, the system automatically binds the object to all local interfaces and chooses an ephemeral port as soon as the first datagram is sent. After the local address is set, either automatically by the system or explicitly by setsockname, it cannot be changed.

PARAMETERS

address string
an IP address or a host name. If address is "*" the system binds to all local interfaces using the constant INADDR_ANY.
port number
the port number. If port is 0, the system chooses an ephemeral port.

RETURNS

success number
nil
the value 1 on success, or nil in case of error.
error string
nil
the error message, or nil if no error occurred.

unconnected:settimeout()

unconnected:settimeout([value:number|nil])→success:number

Changes the timeout values for the object. By default, the receive and receivefrom operations are blocking. That is, any call to the methods will block indefinitely, until data arrives. The settimeout function defines a limit on the amount of time the functions can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code. In UDP, the send and sendto methods never block (the datagram is just passed to the OS and the call returns immediately). Therefore, the settimeout method has no effect on them.

PARAMETERS

[value] number
nil
the amount of time to wait, in seconds. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.

RETURNS

success number
the value 1.

Constants

socket._SETSIZE

This constant contains the maximum number of sockets that the select function can handle.

value integer

socket._VERSION

This constant has a string describing the current LuaSocket version.

value string