This module implements a high-level cross-platform sockets interface.
Types
SocketImpl = object fd: SocketHandle case isBuffered: bool of true: buffer: array[0 .. BufferSize, char] currPos: int bufLen: int of false: nil when defined(ssl): case isSsl: bool of true: sslHandle: SSLPtr sslContext: SSLContext sslNoHandshake: bool sslHasPeekChar: bool sslPeekChar: char of false: nil lastError: OSErrorCode ## stores the last error on this socket domain: Domain sockType: SockType protocol: Protocol
- socket type Source
Socket = ref SocketImpl
- Source
SOBool = enum OptAcceptConn, OptBroadcast, OptDebug, OptDontRoute, OptKeepAlive, OptOOBInline, OptReuseAddr
- Boolean socket options. Source
ReadLineResult = enum ReadFullLine, ReadPartialLine, ReadDisconnected, ReadNone
- result for readLineAsync Source
TimeoutError = object of Exception
- Source
SocketFlag = enum Peek, SafeDisconn ## Ensures disconnection exceptions (ECONNRESET, EPIPE etc) are not thrown.
- Source
IpAddressFamily = enum IPv6, ## IPv6 address IPv4 ## IPv4 address
- Describes the type of an IP address Source
IpAddress = object case family*: IpAddressFamily ## the type of the IP address (IPv4 or IPv6) of IpAddressFamily.IPv6: address_v6*: array[0 .. 15, uint8] ## Contains the IP address in bytes in ## case of IPv6 of IpAddressFamily.IPv4: address_v4*: array[0 .. 3, uint8] ## Contains the IP address in bytes in ## case of IPv4
- stores an arbitrary IP address Source
Procs
proc isDisconnectionError(flags: set[SocketFlag]; lastError: OSErrorCode): bool {. raises: [], tags: [].}
- Determines whether lastError is a disconnection error. Only does this if flags contains SafeDisconn. Source
proc toOSFlags(socketFlags: set[SocketFlag]): cint {.raises: [], tags: [].}
- Converts the flags into the underlying OS representation. Source
proc newSocket(fd: SocketHandle; domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP; buffered = true): Socket {.raises: [], tags: [].}
- Creates a new socket as specified by the params. Source
proc newSocket(domain, sockType, protocol: cint; buffered = true): Socket {. raises: [OSError], tags: [].}
-
Creates a new socket.
If an error occurs EOS will be raised.
Source proc newSocket(domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP; buffered = true): Socket {. raises: [OSError], tags: [].}
-
Creates a new socket.
If an error occurs EOS will be raised.
Source proc getSocketError(socket: Socket): OSErrorCode {.raises: [OSError], tags: [].}
- Checks osLastError for a valid error. If it has been reset it uses the last error stored in the socket object. Source
proc socketError(socket: Socket; err: int = - 1; async = false; lastError = -1.OSErrorCode): void {. raises: [OSError], tags: [].}
-
Raises an OSError based on the error code returned by SSLGetError (for SSL sockets) and osLastError otherwise.
If async is true no error will be thrown in the case when the error was caused by no data being available to be read.
If err is not lower than 0 no exception will be raised.
Source proc listen(socket: Socket; backlog = SOMAXCONN) {.tags: [ReadIOEffect], raises: [OSError].}
-
Marks socket as accepting connections. Backlog specifies the maximum length of the queue of pending connections.
Raises an EOS error upon failure.
Source proc bindAddr(socket: Socket; port = Port(0); address = "") {.tags: [ReadIOEffect], raises: [OSError].}
-
Binds address:port to the socket.
If address is "" then ADDR_ANY will be bound.
Source proc acceptAddr(server: Socket; client: var Socket; address: var string; flags = {SafeDisconn}) {.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [OSError].}
-
Blocks until a connection is being made from a client. When a connection is made sets client to the client socket and address to the address of the connecting client. This function will raise EOS if an error occurs.
The resulting client will inherit any properties of the server socket. For example: whether the socket is buffered or not.
Note: client must be initialised (with new), this function makes no effort to initialise the client variable.
The accept call may result in an error if the connecting socket disconnects during the duration of the accept. If the SafeDisconn flag is specified then this error will not be raised and instead accept will be called again.
Source proc accept(server: Socket; client: var Socket; flags = {SafeDisconn}) {. tags: [ReadIOEffect], raises: [OSError].}
-
Equivalent to acceptAddr but doesn't return the address, only the socket.
Note: client must be initialised (with new), this function makes no effort to initialise the client variable.
The accept call may result in an error if the connecting socket disconnects during the duration of the accept. If the SafeDisconn flag is specified then this error will not be raised and instead accept will be called again.
Source proc close(socket: Socket) {.raises: [], tags: [].}
- Closes a socket. Source
proc toCInt(opt: SOBool): cint {.raises: [], tags: [].}
- Converts a SOBool into its Socket Option cint representation. Source
proc getSockOpt(socket: Socket; opt: SOBool; level = SOL_SOCKET): bool {. tags: [ReadIOEffect], raises: [OSError].}
- Retrieves option opt as a boolean value. Source
proc getLocalAddr(socket: Socket): (string, Port) {.raises: [OSError], tags: [].}
- Source
proc getPeerAddr(socket: Socket): (string, Port) {.raises: [OSError], tags: [].}
- Source
proc setSockOpt(socket: Socket; opt: SOBool; value: bool; level = SOL_SOCKET) {. tags: [WriteIOEffect], raises: [OSError].}
- Sets option opt to a boolean value specified by value. Source
proc connect(socket: Socket; address: string; port = Port(0)) {.tags: [ReadIOEffect], raises: [OSError].}
-
Connects socket to address:port. Address can be an IP address or a host name. If address is a host name, this function will try each IP of that host name. htons is already performed on port so you must not do it.
If socket is an SSL socket a handshake will be automatically performed.
Source proc hasDataBuffered(s: Socket): bool {.raises: [], tags: [].}
- Determines whether a socket has data buffered. Source
proc recv(socket: Socket; data: pointer; size: int): int {.tags: [ReadIOEffect], raises: [].}
-
Receives data from a socket.
Note: This is a low-level function, you may be interested in the higher level versions of this function which are also named recv.
Source proc recv(socket: Socket; data: pointer; size: int; timeout: int): int {. tags: [ReadIOEffect, TimeEffect], raises: [TimeoutError, OSError].}
- overload with a timeout parameter in milliseconds. Source
proc recv(socket: Socket; data: var string; size: int; timeout = - 1; flags = {SafeDisconn}): int {. raises: [TimeoutError, OSError], tags: [ReadIOEffect, TimeEffect].}
-
Higher-level version of recv.
When 0 is returned the socket's connection has been closed.
This function will throw an EOS exception when an error occurs. A value lower than 0 is never returned.
A timeout may be specified in milliseconds, if enough data is not received within the time specified an ETimeout exception will be raised.
Note: data must be initialised.
Warning: Only the SafeDisconn flag is currently supported.
Source proc readLine(socket: Socket; line: var TaintedString; timeout = - 1; flags = {SafeDisconn}) {.tags: [ReadIOEffect, TimeEffect], raises: [TimeoutError, OSError].}
-
Reads a line of data from socket.
If a full line is read \r\L is not added to line, however if solely \r\L is read then line will be set to it.
If the socket is disconnected, line will be set to "".
An EOS exception will be raised in the case of a socket error.
A timeout can be specified in milliseconds, if data is not received within the specified time an ETimeout exception will be raised.
Warning: Only the SafeDisconn flag is currently supported.
Source proc recvFrom(socket: Socket; data: var string; length: int; address: var string; port: var Port; flags = 0'i32): int {.tags: [ReadIOEffect], raises: [OSError].}
-
Receives data from socket. This function should normally be used with connection-less sockets (UDP sockets).
If an error occurs an EOS exception will be raised. Otherwise the return value will be the length of data received.
Warning: This function does not yet have a buffered implementation, so when socket is buffered the non-buffered implementation will be used. Therefore if socket contains something in its buffer this function will make no effort to return it.
Source proc skip(socket: Socket; size: int; timeout = - 1) {. raises: [Exception, TimeoutError, OSError], tags: [TimeEffect, ReadIOEffect].}
-
Skips size amount of bytes.
An optional timeout can be specified in milliseconds, if skipping the bytes takes longer than specified an ETimeout exception will be raised.
Returns the number of skipped bytes.
Source proc send(socket: Socket; data: pointer; size: int): int {.tags: [WriteIOEffect], raises: [].}
-
Sends data to a socket.
Note: This is a low-level version of send. You likely should use the version below.
Source proc send(socket: Socket; data: string; flags = {SafeDisconn}) {.tags: [WriteIOEffect], raises: [OSError].}
- sends data to a socket. Source
proc trySend(socket: Socket; data: string): bool {.tags: [WriteIOEffect], raises: [].}
- Safe alternative to send. Does not raise an EOS when an error occurs, and instead returns false on failure. Source
proc sendTo(socket: Socket; address: string; port: Port; data: pointer; size: int; af: Domain = AF_INET; flags = 0'i32): int {.tags: [WriteIOEffect], raises: [OSError].}
-
This proc sends data to the specified address, which may be an IP address or a hostname, if a hostname is specified this function will try each IP of that hostname.
Note: You may wish to use the high-level version of this function which is defined below.
Note: This proc is not available for SSL sockets.
Source proc sendTo(socket: Socket; address: string; port: Port; data: string): int {. tags: [WriteIOEffect], raises: [OSError].}
-
This proc sends data to the specified address, which may be an IP address or a hostname, if a hostname is specified this function will try each IP of that hostname.
This is the high-level version of the above sendTo function.
Source proc connect(socket: Socket; address: string; port = Port(0); timeout: int) {. tags: [ReadIOEffect, WriteIOEffect], raises: [OSError, TimeoutError].}
-
Connects to server as specified by address on port specified by port.
The timeout paremeter specifies the time in milliseconds to allow for the connection to the server to be made.
Source proc isSsl(socket: Socket): bool {.raises: [], tags: [].}
- Determines whether socket is a SSL socket. Source
proc getFd(socket: Socket): SocketHandle {.raises: [], tags: [].}
- Returns the socket's file descriptor Source
proc IPv4_any(): IpAddress {.raises: [], tags: [].}
- Returns the IPv4 any address, which can be used to listen on all available network adapters Source
proc IPv4_loopback(): IpAddress {.raises: [], tags: [].}
- Returns the IPv4 loopback address (127.0.0.1) Source
proc IPv4_broadcast(): IpAddress {.raises: [], tags: [].}
- Returns the IPv4 broadcast address (255.255.255.255) Source
proc IPv6_any(): IpAddress {.raises: [], tags: [].}
- Returns the IPv6 any address (::0), which can be used to listen on all available network adapters Source
proc IPv6_loopback(): IpAddress {.raises: [], tags: [].}
- Returns the IPv6 loopback address (::1) Source
proc `==`(lhs, rhs: IpAddress): bool {.raises: [], tags: [].}
- Compares two IpAddresses for Equality. Returns two if the addresses are equal Source
proc `$`(address: IpAddress): string {.raises: [], tags: [].}
- Converts an IpAddress into the textual representation Source
proc parseIpAddress(address_str: string): IpAddress {.raises: [ValueError], tags: [].}
- Parses an IP address Raises EInvalidValue on error Source
proc isIpAddress(address_str: string): bool {.tags: [], raises: [].}
- Checks if a string is an IP address Returns true if it is, false otherwise Source