Module socket

Low-level Lua interface for kernel networking sockets.

This library provides support for creating and managing various types of sockets within the Linux kernel, enabling network communication directly from Lua scripts running in kernel space. It is inspired by Chengzhi Tan's GSoC project.

It allows operations such as creating sockets, binding, listening, connecting, sending, and receiving data. The library also exposes constants for address families, socket types, IP protocols, and message flags.

For higher-level IPv4 TCP/UDP socket operations with string-based IP addresses (e.g., "127.0.0.1"), consider using the socket.inet library.

See also:

Class socket

socket:accept (self[, flags=0]) Accepts a connection on a listening socket.
socket:bind (addr[, port]) Binds the socket to a local address.
socket:close () Closes the socket.
socket:connect (addr[, port[, flags=0]]) Initiates a connection on a socket.
socket:getpeername () Gets the address of the peer to which the socket is connected.
socket:getsockname () Gets the local address to which the socket is bound.
socket:listen ([backlog]) Puts a connection-oriented socket into the listening state.
socket:receive (length[, flags=0[, from=false]]) Receives a message from the socket.
socket:send (message[, addr[, port]]) Sends a message through the socket.

socket

af Table of address family constants.
ipproto Table of IP protocol constants.
msg Table of message flags.
new (family, type, protocol) Creates a new socket object.
sock Table of socket type and flag constants.


Class socket

Represents a kernel socket object. This is a userdata object returned by socket.new() or sock:accept(). It encapsulates a kernel struct socket and provides methods for network operations.
socket:accept (self[, flags=0])
Accepts a connection on a listening socket. This function is used with connection-oriented sockets (e.g., SOCK_STREAM) that have been put into the listening state by sock:listen().

Parameters:

  • self socket The listening socket object.
  • flags integer Optional flags to apply to the newly accepted socket (e.g., socket.sock.NONBLOCK, socket.sock.CLOEXEC). (default 0)

Returns:

    socket A new socket object representing the accepted connection.

Raises:

Error if the accept operation fails.
socket:bind (addr[, port])
Binds the socket to a local address. This is typically used on the server side before calling listen() or on connectionless sockets to specify a local port/interface for receiving.

Parameters:

  • addr integer or string

    The local address to bind to. The interpretation depends on socket.sk.sk_family:

    • AF_INET (IPv4): An integer representing the IPv4 address (e.g., from net.aton()). Use 0 (or net.aton("0.0.0.0")) to bind to all available interfaces. The port argument is also required.
    • AF_PACKET:
      • If addr is an integer: It's treated as the network interface index (e.g., from linux.ifindex("eth0")). The sll_protocol field of the underlying sockaddr_ll structure would need to be set to htons(ETH_P_ALL) or similar if not binding to a specific protocol via other means (e.g. socket.new's protocol argument for AF_PACKET might set this).
      • If addr is a string: It's a packed string directly representing parts of the sockaddr_ll structure (specifically, the fields after sll_family, like sll_protocol). Example from tap.lua for binding to ETH_P_ALL (0x0003): sock:bind(string.pack(">H", 0x0003)).
    • Other families: A packed string representing the family-specific address structure.
  • port integer The local port number (required and used only if the family is AF_INET). (optional)

Returns:

    nil

Raises:

Error if the bind operation fails (e.g., address already in use, invalid address).

See also:

Usage:

    -- Bind TCP/IPv4 socket to localhost, port 8080
    tcp_server_sock:bind(net.aton("127.0.0.1"), 8080)
    
    -- Bind AF_PACKET socket to receive all protocols (ETH_P_ALL = 0x0003)
    af_packet_sock:bind(string.pack(">H", 0x0003))
socket:close ()
Closes the socket. This shuts down the socket for both reading and writing and releases associated kernel resources. This method is also called automatically when the socket object is garbage collected or via Lua 5.4's to-be-closed mechanism.

Returns:

    nil
socket:connect (addr[, port[, flags=0]])
Initiates a connection on a socket. This is typically used by client sockets to establish a connection to a server. For datagram sockets, this sets the default destination address for send and the only address from which datagrams are received.

Parameters:

  • addr integer or string

    The destination address to connect to. Interpretation depends on socket.sk.sk_family:

    • AF_INET (IPv4): An integer representing the IPv4 address (e.g., from net.aton()). The port argument is also required.
    • Other families: A packed string representing the family-specific destination address.
  • port integer The destination port number (required and used only if the family is AF_INET). (optional)
  • flags integer Optional connection flags. (default 0)

Returns:

    nil

Raises:

Error if the connect operation fails (e.g., connection refused, host unreachable).

Usage:

    tcp_client_sock:connect(net.aton("192.168.1.100"), 80)
socket:getpeername ()
Gets the address of the peer to which the socket is connected. This is typically used with connection-oriented sockets after a connection has been established, or with connectionless sockets after connect() has been called to set a default peer.

Returns:

  1. integer or string

    addr The peer's address.

    • For AF_INET: An integer representing the IPv4 address (can be converted with net.ntoa()).
    • For other families: A packed string representing the peer's address.
  2. integer port If the family is AF_INET, the peer's port number.

Raises:

Error if the operation fails (e.g., socket not connected).

Usage:

    local peer_ip_int, peer_port = connected_socket:getpeername()
    if connected_socket.sk.sk_family == socket.af.INET then print("Connected to " .. net.ntoa(peer_ip_int) .. ":" .. peer_port) end
socket:getsockname ()
Gets the local address to which the socket is bound.

Returns:

  1. integer or string

    addr The local address.

    • For AF_INET: An integer representing the IPv4 address (can be converted with net.ntoa()).
    • For other families: A packed string representing the local address.
  2. integer port If the family is AF_INET, the local port number.

Raises:

Error if the operation fails.

Usage:

    local local_ip_int, local_port = my_socket:getsockname()
    if my_socket.sk.sk_family == socket.af.INET then print("Bound to " .. net.ntoa(local_ip_int) .. ":" .. local_port) end
socket:listen ([backlog])
Puts a connection-oriented socket into the listening state. This is required for server sockets (e.g., SOCK_STREAM) to be able to accept incoming connections.

Parameters:

  • backlog integer The maximum length of the queue for pending connections. If omitted, a system-dependent default (e.g., SOMAXCONN) is used. (optional)

Returns:

    nil

Raises:

Error if the listen operation fails (e.g., socket not bound, invalid state).

Usage:

    tcp_server_sock:listen(10)
socket:receive (length[, flags=0[, from=false]])
Receives a message from the socket.

Parameters:

  • length integer The maximum number of bytes to receive.
  • flags integer Optional message flags (e.g., socket.msg.PEEK). See the socket.msg table for available flags. These can be OR'd together. (default 0)
  • from boolean If true, the function also returns the sender's address and port (for AF_INET). This is typically used with connectionless sockets (SOCK_DGRAM). (default false)

Returns:

  1. string The received message (as a string of bytes).
  2. integer or string addr If from is true, the sender's address. - For AF_INET: An integer representing the IPv4 address (can be converted with net.ntoa()). - For other families: A packed string representing the sender's address.
  3. integer port If from is true and the family is AF_INET, the sender's port number.

Raises:

Error if the receive operation fails.

See also:

Usage:

    -- For a connected TCP socket:
    local data = tcp_conn_sock:receive(1024)
    if data then print("Received:", data) end
    
    -- For a UDP socket, getting sender info:
    local data, sender_ip_int, sender_port = udp_sock:receive(1500, 0, true)
    if data then print("Received from " .. net.ntoa(sender_ip_int) .. ":" .. sender_port .. ": " .. data) end
socket:send (message[, addr[, port]])
Sends a message through the socket.

For connection-oriented sockets (SOCK_STREAM), addr and port are usually omitted as the connection is already established. For connectionless sockets (SOCK_DGRAM), addr and port (if applicable for the address family) specify the destination.

Parameters:

  • message string The string message to send.
  • addr integer or string

    The destination address.

    • For AF_INET (IPv4) sockets: An integer representing the IPv4 address (e.g., from net.aton()).
    • For other address families (e.g., AF_PACKET): A packed string representing the destination address (e.g., MAC address for AF_PACKET). The exact format depends on the family.
    (optional)
  • port integer The destination port number (required if addr is an IPv4 address for AF_INET). (optional)

Returns:

    integer The number of bytes sent.

Raises:

Error if the send operation fails or if address parameters are incorrect for the socket type.

See also:

Usage:

    -- For a connected TCP socket:
    local bytes_sent = tcp_conn_sock:send("Hello, server!")
    
    -- For a UDP socket (sending to 192.168.1.100, port 1234):
    local bytes_sent = udp_sock:send("UDP packet", net.aton("192.168.1.100"), 1234)

socket

af
Table of address family constants. These constants are used in socket.new() to specify the communication domain of the socket. (Constants from <linux/socket.h>)

Fields:

  • UNSPEC integer Unspecified.
  • UNIX integer Unix domain sockets.
  • LOCAL integer POSIX name for AF_UNIX.
  • INET integer Internet IP Protocol (IPv4).
  • AX25 integer Amateur Radio AX.25.
  • IPX integer Novell IPX.
  • APPLETALK integer AppleTalk DDP.
  • NETROM integer Amateur Radio NET/ROM.
  • BRIDGE integer Multiprotocol bridge.
  • ATMPVC integer ATM PVCs.
  • X25 integer Reserved for X.25 project.
  • INET6 integer IP version 6.
  • ROSE integer Amateur Radio X.25 PLP.
  • DECnet integer Reserved for DECnet project.
  • NETBEUI integer Reserved for 802.2LLC project.
  • SECURITY integer Security callback pseudo AF.
  • KEY integer PF_KEY key management API.
  • NETLINK integer Netlink.
  • ROUTE integer Alias to emulate 4.4BSD.
  • PACKET integer Packet family.
  • ASH integer Ash.
  • ECONET integer Acorn Econet.
  • ATMSVC integer ATM SVCs.
  • RDS integer RDS sockets.
  • SNA integer Linux SNA Project.
  • IRDA integer IRDA sockets.
  • PPPOX integer PPPoX sockets.
  • WANPIPE integer Wanpipe API Sockets.
  • LLC integer Linux LLC.
  • IB integer Native InfiniBand address.
  • MPLS integer MPLS.
  • CAN integer Controller Area Network.
  • TIPC integer TIPC sockets.
  • BLUETOOTH integer Bluetooth sockets.
  • IUCV integer IUCV sockets.
  • RXRPC integer RxRPC sockets.
  • ISDN integer mISDN sockets.
  • PHONET integer Phonet sockets.
  • IEEE802154 integer IEEE802154 sockets.
  • CAIF integer CAIF sockets.
  • ALG integer Algorithm sockets.
  • NFC integer NFC sockets.
  • VSOCK integer vSockets.
  • KCM integer Kernel Connection Multiplexor.
  • QIPCRTR integer Qualcomm IPC Router.
  • SMC integer SMCP sockets (PFSMC reuses AFINET).
  • XDP integer XDP sockets.
  • MCTP integer Management component transport protocol (Kernel 5.15+).
  • MAX integer Maximum value for AF constants.
ipproto
Table of IP protocol constants. These are used in socket.new() to specify the protocol for AF_INET or AF_INET6 sockets. (Constants from <uapi/linux/in.h>)

Fields:

  • IP integer Dummy protocol for TCP. (Typically 0)
  • ICMP integer Internet Control Message Protocol.
  • IGMP integer Internet Group Management Protocol.
  • IPIP integer IPIP tunnels.
  • TCP integer Transmission Control Protocol.
  • EGP integer Exterior Gateway Protocol.
  • PUP integer PUP protocol.
  • UDP integer User Datagram Protocol.
  • IDP integer XNS IDP protocol.
  • TP integer SO Transport Protocol Class 4.
  • DCCP integer Datagram Congestion Control Protocol.
  • IPV6 integer IPv6-in-IPv4 tunnelling.
  • RSVP integer RSVP Protocol.
  • GRE integer Cisco GRE tunnels.
  • ESP integer Encapsulation Security Payload protocol.
  • AH integer Authentication Header protocol.
  • MTP integer Multicast Transport Protocol.
  • BEETPH integer IP option pseudo header for BEET.
  • ENCAP integer Encapsulation Header.
  • PIM integer Protocol Independent Multicast.
  • COMP integer Compression Header Protocol.
  • L2TP integer Layer Two Tunneling Protocol.
  • SCTP integer Stream Control Transport Protocol.
  • UDPLITE integer UDP-Lite (RFC 3828).
  • MPLS integer MPLS in IP (RFC 4023).
  • ETHERNET integer Ethernet-within-IPv6 Encapsulation (Kernel 5.6+).
  • RAW integer Raw IP packets.
  • MPTCP integer Multipath TCP connection (Kernel 5.6+).
msg
Table of message flags. These flags can be used with sock:receive() and sock:send() to modify their behavior. (Constants from <linux/socket.h>)

Fields:

  • OOB integer Process out-of-band data.
  • PEEK integer Peek at incoming message without removing it from the queue.
  • DONTROUTE integer Don't use a gateway to send out the packet.
  • TRYHARD integer Synonym for DONTROUTE for DECnet.
  • CTRUNC integer Control data lost before delivery.
  • PROBE integer Do not send data, only probe path (e.g., for MTU discovery).
  • TRUNC integer Normal data lost before delivery.
  • DONTWAIT integer Enables non-blocking operation.
  • EOR integer Terminates a record (if supported by the protocol).
  • WAITALL integer Wait for full request or error.
  • FIN integer FIN segment.
  • SYN integer SYN segment.
  • CONFIRM integer Confirm path validity (e.g., ARP entry).
  • RST integer RST segment.
  • ERRQUEUE integer Fetch message from error queue.
  • NOSIGNAL integer Do not generate SIGPIPE.
  • MORE integer Sender will send more data.
  • WAITFORONE integer For recvmmsg(): block until at least one packet is available.
  • SENDPAGE_NOPOLICY integer Internal: sendpage() should not apply policy.
  • BATCH integer For sendmmsg(): more messages are coming.
  • EOF integer End of file.
  • NO_SHARED_FRAGS integer Internal: sendpage() page fragments are not shared.
  • SENDPAGE_DECRYPTED integer Internal: sendpage() page may carry plain text and require encryption.
  • ZEROCOPY integer Use user data in kernel path for zero-copy transmit.
  • FASTOPEN integer Send data in TCP SYN (TCP Fast Open).
  • CMSG_CLOEXEC integer Set close-on-exec for file descriptor received via SCM_RIGHTS.
new (family, type, protocol)
Creates a new socket object. This function is the primary way to create a socket.

Parameters:

  • family integer The address family for the socket (e.g., socket.af.INET).
  • type integer The type of the socket (e.g., socket.sock.STREAM).
  • protocol integer The protocol to be used (e.g., socket.ipproto.TCP). For AF_PACKET sockets, protocol is typically an ETH_P_* value in network byte order (e.g., linux.hton16(0x0003) for ETH_P_ALL).

Returns:

    socket A new socket object.

Raises:

Error if socket creation fails.

See also:

Usage:

    -- TCP/IPv4 socket
    local tcp_sock = socket.new(socket.af.INET, socket.sock.STREAM, socket.ipproto.TCP)
sock
Table of socket type and flag constants. Socket types are used in socket.new(). Socket flags can be used in socket.new() (by ORing with type), sock:accept(), and sock:connect(). (Constants from <linux/net.h>)

Fields:

  • STREAM integer Stream socket (e.g., TCP).
  • DGRAM integer Datagram socket (e.g., UDP).
  • RAW integer Raw socket.
  • RDM integer Reliably-delivered message socket.
  • SEQPACKET integer Sequential packet socket.
  • DCCP integer Datagram Congestion Control Protocol socket.
  • PACKET integer Linux specific packet socket (deprecated in favor of AF_PACKET).
  • CLOEXEC integer Atomically set the close-on-exec flag for the new socket.
  • NONBLOCK integer Atomically set the O_NONBLOCK flag for the new socket.
generated by LDoc 1.5.0 Last updated 2025-06-27 17:53:55