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

Throws an exception in case of error.

socket.udp()

Creates and returns an unconnected UDP object.

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

  • host : local address to bind to

  • port : local port to bind

  • backlogorhook : Optionally, user can also specify the backlog argument to the listen method (defaults to 32). This third parameter can also be the hook if no backlog parameter is given. -@param hook is an additional parameter (not compatible with luasocket original socket.bind()

Return value

TCP server object

Usages:

  • socket.bind("someaddress", 4242, function hook(...) end)
  • socket.bind("someaddress", 4242, 32,function hook(...) end)
    
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

  • address : address to connect to

  • port : port

  • locaddr : optional local address to bind

  • locport : optional local port to bind

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

  • finalizer : function that will be called before try throws the exception.

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

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

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.

  • Important note: 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.

  • Another important note: calling select with a server socket in the receive parameter before a call to server.accept does not guarantee accept will return immediately. Use the settimeout method or accept might block forever.

  • Yet another note: If you close a socket and pass it to select, it will be ignored.

Parameters

  • recvt : an array with the sockets to test for characters available for reading. Can also be empty table or nil. Non-socket values (or values with non-numeric indices) in the array will be silently ignored.

  • sendt : an array of sockets that are watched to see if it is OK to immediately write on them. Can also be empty table or nil. Non-socket values (or values with non-numeric indices) in the array will be silently ignored.

  • timeout : optional 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.

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

  • mode : Defines the behavior of the sink. The following options are available:

    • "http-chunked": sends data through socket after applying the chunked transfer coding, closing the socket when done;
    • "close-when-done": sends all received data through the socket, closing the socket when done;
    • "keep-open": sends all received data through the socket, leaving it open when done.
  • socket : The stream socket object used to send the data.

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

  • d : The number of arguments to drop.

  • vararg : The arguments.

Return value

retd+1 to retn.

socket.sleep(time)

Freezes the program execution during a given amount of time.

Parameter

  • #number time : Number of seconds to sleep for. The function truncates time down to the nearest integer.

socket.source(mode, socket)

Creates an LTN12 source from a stream socket object.

Parameters

  • mode : Defines the behavior of the source. The following options are available:

    • "http-chunked": receives data from socket and removes the chunked transfer coding before returning the data;
    • "by-length": receives a fixed number of bytes from the socket. This mode requires the extra argument length;
    • "until-closed": receives data from a socket until the other side closes the connection.
  • socket : The stream socket object used to receive the data.

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

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

  • ... : Can be arbitrary arguments, but are usually the return values of a function call nested with try.

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

  • pattern : 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.
  • #string prefix : (optional) An optional string to be concatenated to the beginning of any received data before return.

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:

    • 'closed': In case the connection was closed before the transmission was completed.
    • 'timeout': In case there was a timeout during the operation.

    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

  • data : The string to be sent.

  • #number i : (optional) As in #string.sub.

  • #number j : (optional) As in #string.sub.

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:

    • 'closed': In case the connection was closed before the transmission was completed.
    • 'timeout': In case there was a timeout during the operation.
client:setoption(option, value)

As in server.setoption.

Parameters

  • #string option :

  • value :

client:setstats(received, sent, age)

As in server.setstats.

Parameters

  • #number received :

  • #number sent :

  • #number age :

client:settimeout(value, mode)

As in server.settimeout.

Parameters

  • #number value :

  • #string mode :

client:shutdown(mode)

Shuts down part of a full-duplex connection.

Parameter

  • #string mode : Tells which way of the connection should be shut down and can take the value:

    • "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.

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

  • size :

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

  • datagram : 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.

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

  • value :

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

  • #string address : Can be an IP address or a host name. If address is '*' and the object is connected, the peer association is removed and the object becomes an unconnected object again. In that case, the port argument is ignored.

  • #number port : The port number.

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

  • #number value :

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

  • #string address : Can be an IP address or host name.

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

  • #string address : Can be an IP address or host name.

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

  • address : Can be an IP address or a host name.

  • port : Port must be an integer number in the range [1..64K).

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

  • backlog : Specifies 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.

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

  • #number received :

  • #number sent :

  • #number age :

master:settimeout(value, mode)

As in server.settimeout.

Parameters

  • #number value :

  • #string mode :

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:

    • 'timeout': If a timeout condition is met.
    • Message describing error, for other errors.
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

  • #string option : The option name:

    • '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 a boolean entry 'on' and a numeric entry for the time interval 'timeout' in seconds. 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. I do not advise you 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.
  • value : Depends on the option being set.

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

  • #number received : Number with the new number of bytes received.

  • #number sent : Number with the new number of bytes sent.

  • #number age : is the new age in seconds.

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

  • #number value : The amount of time to wait is specified, in seconds. The #nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.

  • #string mode : There are two timeout modes and both can be used together for fine tuning:

    • '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.

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

  • #number size : optional Specifies the 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).

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

  • #number size :

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

  • datagram : 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 : The IP address of the recipient. Host names are not allowed for performance reasons.

  • port : The port number at the recipient.

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

  • #string option : The option name:

    • 'dontroute': Setting this option to true indicates that outgoing messages should bypass the standard routing facilities;
    • 'broadcast': Setting this option to true requests permission to send broadcast datagrams on the socket.
  • value : Depends on the option being set.

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

  • #string address :

  • #number port :

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

  • address : Can be an IP address or a host name. If address is '*' the system binds to all local interfaces using the constant INADDR_ANY.

  • #number port : If port is 0, the system chooses an ephemeral port.

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

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