Module socket The socket namespace contains the core functionality of LuaSocket.

To obtain the socket namespace, run:

-- loads the socket module local socket = require("socket")

Type client

client:close() As in #server.bind.
client:getpeername() Returns information about the remote side of a connected client object.
client:getsockname() As in #server.getsockname.
client:getstats() As in #server.getstats.
client:receive(pattern, prefix) Reads data from a client object, according to the specified read pattern.
client:send(data, i, j) Sends data through client object.
client:setoption(option, value) As in #server.setoption.
client:setstats(received, sent, age) As in #server.setstats.
client:settimeout(value, mode) As in #server.settimeout.
client:shutdown(mode) Shuts down part of a full-duplex connection.

Type connected

connected:close() As in #unconnected.close.
connected:getpeername() Retrieves information about the peer associated with a connected UDP object.
connected:getsockname() As in #unconnected.getsockname.
connected:receive(size) As in #unconnected.receive.
connected:send(datagram) Sends a datagram to the UDP peer of a connected object.
connected:setoption(value) As in #unconnected.setoption.
connected:setpeername(address, port) Changes the peer of a UDP object.
connected:settimeout(value) As in #unconnected.settimeout.

Type dns

dns.gethostname() The standard host name

dns.tohostname(address) Converts from IP address to host name.
dns.toip(address) Converts from host name to IP address.

Type master

master:close() As in #server.bind.
master:connect(address, port) Attempts to connect a master object to a remote host, transforming it into a client object.
master:getsockname() As in #server.getsockname.
master:getstats() As in #server.getstats.
master:listen(backlog) Specifies the socket is willing to receive connections, transforming the object into a server object.
master:setstats(received, sent, age) As in #server.setstats.
master:settimeout(value, mode) As in #server.settimeout.

Type server

server:accept() Waits for a remote connection on the server object and returns a #client object representing that connection.
server:close() Closes a TCP object.
server:getsockname() Returns the local address information associated to the object.
server:getstats() Returns accounting information on the socket, useful for throttling of bandwidth.
server:setoption(option, value) Sets options for the TCP object.
server:setstats(received, sent, age) Resets accounting information on the socket, useful for throttling of bandwidth.
server:settimeout(value, mode) Changes the timeout values for the object.

Type socket

socket._DEBUG This constant is set to true if the library was compiled with debug support.
socket._VERSION This constant has a string describing the current LuaSocket version.
socket.bind(host, port, backlog_or_hook) This function is a shortcut that creates and returns a TCP server object bound to a local address and port, ready to accept client connections.
socket.connect(address, port, locaddr, locport) This function is a shortcut that creates and returns a TCP client object connected to a remote host at a given port.
socket.dns DNS utilities.
socket.gettime() Gives time
socket.newtry(finalizer) Creates and returns a clean #socket.try function that allows for cleanup before the exception is raised.
socket.protect(func) Converts a function that throws exceptions into a safe function.
socket.select(recvt, sendt, timeout) Waits for a number of sockets to change status.
socket.sink(mode, socket) Creates an LTN12 sink from a stream socket object.
socket.skip(d, vararg) Drops a number of arguments and returns the remaining.
socket.sleep(time) Freezes the program execution during a given amount of time.
socket.source(mode, socket) Creates an LTN12 source from a stream socket object.
socket.tcp() Creates and returns a TCP master object.
socket.try(vararg) Throws an exception in case of error.
socket.udp() Creates and returns an unconnected UDP object.

Type unconnected

unconnected:close() Closes a UDP object.
unconnected:getsockname() Returns the local address information associated to the object.
unconnected:receive(size) Receives a datagram from the UDP object.
unconnected:receivefrom(size) Works exactly as the #unconnected.receive method, except it returns the IP address and port as extra return values (and is therefore slightly less efficient).
unconnected:sendto(datagram, ip, port) Sends a datagram to the specified IP address and port number.
unconnected.setoption(option, value) Sets options for the UDP object.
unconnected:setpeername(address, port) As in #connected.setpeername.
unconnected:setsockname(address, port) Binds the UDP object to a local address.
unconnected:settimeout(value) Changes the timeout values for the object.

Type client

A TCP Client object.

Field(s)

client:close()

As in #server.bind.

client:getpeername()

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

Return values

  1. #string: The IP address of the peer, followed by the port number that peer is using for the connection.
  2. #nil: In case of error.

client:getsockname()

As in #server.getsockname.

client:getstats()

As in #server.getstats.

client:receive(pattern, prefix)

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 all patterns is negligible.

Important note: This function was changed severely. It used to support multiple patterns (but I have never seen this feature used) and now it doesn't anymore. Partial results used to be returned in the same way as successful results. This last feature violated the idea that all functions should return nil on error. Thus it was changed too.

Parameters

Return values

  1. If successful, the method returns the received pattern.
  2. #nil, #string: In case of error, the method returns nil followed by an error message which can be:

    Also, after the error message, the function returns the partial result of the transmission.

client:send(data, i, j)

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.

Note: 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

Return values

  1. If successful, the method returns the index of the last byte within [i, j] that has been sent. Notice that, if i is 1 or absent, this is effectively the total number of bytes sent.
  2. #nil, #string, #number:

    In case of error, the method returns nil, followed by an error message, followed by the index of the last byte within [i, j] that has been sent. You might want to try again from the byte following that. The error message can be:

client:setoption(option, value)

As in #server.setoption.

Parameters

client:setstats(received, sent, age)

As in #server.setstats.

Parameters

client:settimeout(value, mode)

As in #server.settimeout.

Parameters

client:shutdown(mode)

Shuts down part of a full-duplex connection.

Parameter

Return value

#number: This function returns 1.

Type connected

A connected UDP object.

Field(s)

connected:close()

As in #unconnected.close.

connected:getpeername()

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

Return value

The IP address and port number of the peer.

connected:getsockname()

As in #unconnected.getsockname.

connected:receive(size)

As in #unconnected.receive.

Parameter

connected:send(datagram)

Sends a datagram to the UDP peer of a connected object.
Note: 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).

Parameter

Return values

  1. #number: 1, in case of success.
  2. #nil, #string: In error cases, error string is provided.

connected:setoption(value)

As in #unconnected.setoption.

Parameter

connected:setpeername(address, port)

Changes the peer of a UDP object.
This method turns an unconnected UDP object into a connected UDP object or vice versa. 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 unconnected#send and connected#receive methods instead of unconnected#sendto and #unconnected.receivefrom.

Note: 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

Return values

  1. #number: 1, in case of success.
  2. #nil, #string: In error cases, error string is provided.

connected:settimeout(value)

As in #unconnected.settimeout.

Parameter

Type dns

Name resolution functions return all information obtained from the resolver in a table of the form:

resolved = { name = canonic-name, alias = alias-list, ip = ip-address-list }

Note that the alias list can be empty.

Field(s)

dns.gethostname()

The standard host name


Return value

#string: The standard host name for the machine.

dns.tohostname(address)

Converts from IP address to host name.

Parameter

Return values

  1. #string: The canonic host name of the given address, followed by a table with all information returned by the resolver.
  2. #nil, #string: In error cases, error string is provided.

dns.toip(address)

Converts from host name to IP address.

Parameter

Return values

  1. #string, #table: The first IP address found for address, followed by a table with all information returned by the resolver.
  2. #nil, #string: In error cases, error string is provided.

Type master

A TCP Master object.

Field(s)

master:close()

As in #server.bind.

master:connect(address, port)

Attempts to connect a master object to a remote host, transforming it into a client object.
Client objects support methods #client.send, #client.receive, #server.getsockname, #client.getpeername, #server.settimeout, and #server.close.

Note: The function socket.connect is available and is a shortcut for the creation of client sockets.

Note: Starting with LuaSocket 2.0, the settimeout method affects the behavior of connect, causing it to return with an error in case of a timeout. If that happens, you can still call socket.select with the socket in the sendt table. The socket will be writable when the connection is established.

Parameters

master:getsockname()

As in #server.getsockname.

master:getstats()

As in #server.getstats.

master:listen(backlog)

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

Parameter

Return values

  1. #number: 1, in case of success.
  2. #nil, #string: In error cases, error string is provided.

master:setstats(received, sent, age)

As in #server.setstats.

Parameters

master:settimeout(value, mode)

As in #server.settimeout.

Parameters

Type server

A TCP Server object.

Field(s)

server:accept()

Waits for a remote connection on the server object and returns a #client object representing that connection.
Note: 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 #socket.settimeout method or accept might block until another client shows up.

Return values

  1. #client If a connection is successfully initiated.
  2. #nil, #string:

    Given error string can be:

server:close()

Closes a 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.

Note: 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.

server:getsockname()

Returns the local address information associated to the object.

Return values

  1. #string: Local IP address and a number with the port.
  2. #nil: In case of error.

server:getstats()

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

Return value

#number, #number, #number: The number of bytes received, the number of bytes sent, and the age of the socket object in seconds.

server:setoption(option, value)

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.

Note: The given descriptions come from the man pages.

Parameters

Return values

  1. #number: 1 in case of success.
  2. #nil: Otherwise.

server:setstats(received, sent, age)

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

Parameters

Return values

  1. #number: 1 in case of success.
  2. #nil: Otherwise.

server:settimeout(value, mode)

Changes the timeout values for the object.
By default, all I/O operations are blocking. That is, any call to the methods #client.send, #client.receive, and #server.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.

Note: 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.

Note: The old timeout method is deprecated. The name has been changed for sake of uniformity, since all other method names already contained verbs making their imperative nature obvious.

Parameters

Type socket

Field(s)

#boolean socket._DEBUG

This constant is set to true if the library was compiled with debug support.

#string socket._VERSION

This constant has a string describing the current LuaSocket version.

socket.bind(host, port, backlog_or_hook)

This function is a shortcut that creates and returns a TCP server object bound to a local address and port, ready to accept client connections.
Modified from the original Luasocket function to support an optional hook argument.

Parameters

Return value

TCP server object

Usage:

socket.connect(address, port, locaddr, locport)

This function is a shortcut that creates and returns a TCP client object connected to a remote host at a given port.
Optionally, the user can also specify the local address and port to bind (locaddr and locport).

Parameters

Return value

TCP client object

#dns socket.dns

DNS utilities.

socket.gettime()

Gives time

Return value

The time in seconds, relative to the origin of the universe. You should subtract the values returned by this function to get meaningful values.

Usage:


 t = socket.gettime()
 -- do stuff
 print(socket.gettime() - t .. " seconds elapsed")

socket.newtry(finalizer)

Creates and returns a clean #socket.try function that allows for cleanup before the exception is raised.

finalizer is a function that will be called before try throws the exception. It will be called in protected mode.

The function returns your customized #socket.try function.

Note: This idea saved a lot of work with the implementation of protocols in LuaSocket:

foo = socket.protect(function() -- connect somewhere local c = socket.try(socket.connect("somewhere", 42)) -- 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() end)

Parameter

Return value

a customized #socket.try function

socket.protect(func)

Converts a function that throws exceptions into a safe function.
This function only catches exceptions thrown by the #socket.try and #socket.newtry functions. It does not catch normal Lua errors.

func is a function that calls #socket.try (or assert, or error) to throw exceptions.

Returns an equivalent function that instead of throwing exceptions, returns nil followed by an error message.

Note: 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 the try function uses errors as the mechanism to throw exceptions.

Parameter

Return value

an equivalent function that instead of throwing exceptions, returns nil followed by an error message

socket.select(recvt, sendt, timeout)

Waits for a number of sockets to change status.

Recvt is an array with the sockets to test for characters available for reading. Sockets in the sendt array are watched to see if it is OK to immediately write on them. Timeout is the maximum amount of time (in seconds) to wait for a change in status. A nil, negative or omitted timeout value allows the function to block indefinitely. Recvt and sendt can also be empty tables or nil. Non-socket values (or values with non-numeric indices) in the arrays will be silently ignored.

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.

Parameters

Return value

a list with the sockets ready for reading, a list with the sockets ready for writing and an error message.

socket.sink(mode, socket)

Creates an LTN12 sink from a stream socket object.

Parameters

Return value

A sink with the appropriate behavior.

socket.skip(d, vararg)

Drops a number of arguments and returns the remaining.

Note: This function is useful to avoid creation of dummy variables:

-- get the status code and separator from SMTP server reply local code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))

Parameters

Return value

retd+1 to retn.

socket.sleep(time)

Freezes the program execution during a given amount of time.

Parameter

socket.source(mode, socket)

Creates an LTN12 source from a stream socket object.

Parameters

Return value

A source with the appropriate behavior.

socket.tcp()

Creates and returns a 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.

Return values

  1. #master In case of success.
  2. #nil, #string: In error cases, error string is provided.

socket.try(vararg)

Throws an exception in case of error.
The exception can only be caught by the protect function. It does not explode into an error message.

Parameter

Usage:


 -- connects or throws an exception with the appropriate error message
 c = socket.try(socket.connect("localhost", 80))

socket.udp()

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

Return values

  1. In case of success, a new unconnected UDP object returned.
  2. #nil, #string: In case of error, nil is returned, followed by an error message.

Type unconnected

A unconnected UDP object.

Field(s)

unconnected:close()

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.

Note: 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.

unconnected:getsockname()

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

Return values

  1. #string: With local IP address and a number with the port.
  2. #nil: In case of error.

unconnected:receive(size)

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.

Parameter

Return values

  1. The received datagram, in case of success.
  2. #nil, #string: #nil followed by the string 'timeout', in case of timeout.

unconnected:receivefrom(size)

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

Parameter

Return value

address, port

unconnected:sendto(datagram, ip, port)

Sends a datagram to the specified IP address and port number.
Note: 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

Return values

  1. #number: 1, in case of success.
  2. #nil, #string: In error cases, error string is provided.

unconnected.setoption(option, value)

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.

Note: The descriptions above come from the man pages.

Parameters

Return values

  1. #number: 1, in case of success.
  2. #nil, #string: In error cases, error string is provided.

unconnected:setpeername(address, port)

As in #connected.setpeername.

Parameters

unconnected:setsockname(address, port)

Binds the UDP object to a local address.
Note: 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

Return value

#nil, #string: In error cases, error string is provided.

unconnected:settimeout(value)

Changes the timeout values for the object.
By default, the #unconnected.receive and #unconnected.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.

Note: In UDP, the #connected.send and #unconnected.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.

Note: The old timeout method is deprecated. The name has been changed for sake of uniformity, since all other method names already contained verbs making their imperative nature obvious.

Parameter