Warning: Since version 0.10.2 this module is deprecated. Use the net or the nativesockets module instead.
This module implements portable sockets, it supports a mix of different types of sockets. Sockets are buffered by default meaning that data will be received in BufferSize (4000) sized chunks, buffering behaviour can be disabled by setting the buffered parameter when calling the socket function to false. Be aware that some functions may not yet support buffered sockets (mainly the recvFrom function).
Most procedures raise OSError on error, but some may return -1 or a boolean false.
SSL is supported through the OpenSSL library. This support can be activated by compiling with the -d:ssl switch. When an SSL socket is used it will raise SslError exceptions when SSL errors occur.
Asynchronous sockets are supported, however a better alternative is to use the asyncio module.
Types
Socket = ref SocketImpl
- Source Edit
Port = distinct uint16
- port type Source Edit
Domain = enum AF_UNIX, ## for local socket (using a file). Unsupported on Windows. AF_INET = 2, ## for network protocol IPv4 or AF_INET6 = 23 ## for network protocol IPv6.
- domain, which specifies the protocol family of the created socket. Other domains than those that are listed here are unsupported. Source Edit
SockType = enum SOCK_STREAM = 1, ## reliable stream-oriented service or Stream Sockets SOCK_DGRAM = 2, ## datagram service or Datagram Sockets SOCK_RAW = 3, ## raw protocols atop the network layer. SOCK_SEQPACKET = 5 ## reliable sequenced packet service
- second argument to socket proc Source Edit
Protocol = enum IPPROTO_TCP = 6, ## Transmission control protocol. IPPROTO_UDP = 17, ## User datagram protocol. IPPROTO_IP, ## Internet protocol. Unsupported on Windows. IPPROTO_IPV6, ## Internet Protocol Version 6. Unsupported on Windows. IPPROTO_RAW, ## Raw IP Packets Protocol. Unsupported on Windows. IPPROTO_ICMP ## Control message protocol. Unsupported on Windows.
- third argument to socket proc Source Edit
Servent = object name*: string aliases*: seq[string] port*: Port proto*: string
- information about a service Source Edit
Hostent = object name*: string aliases*: seq[string] addrtype*: Domain length*: int addrList*: seq[string]
- information about a given host Source Edit
SOBool = enum OptAcceptConn, OptBroadcast, OptDebug, OptDontRoute, OptKeepAlive, OptOOBInline, OptReuseAddr
- Boolean socket options. Source Edit
RecvLineResult = enum RecvFullLine, RecvPartialLine, RecvDisconnected, RecvFail
- result for recvLineAsync Source Edit
ReadLineResult = enum ReadFullLine, ReadPartialLine, ReadDisconnected, ReadNone
- result for readLineAsync Source Edit
TimeoutError = object of Exception
- Source Edit
Procs
proc `==`(a, b: Port): bool {...}{.borrow.}
- == for ports. Source Edit
proc `$`(p: Port): string {...}{.borrow.}
- returns the port number as a string Source Edit
proc ntohl(x: int32): int32 {...}{.raises: [], tags: [].}
- Converts 32-bit integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. Source Edit
proc ntohs(x: int16): int16 {...}{.raises: [], tags: [].}
- Converts 16-bit integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. Source Edit
proc htonl(x: int32): int32 {...}{.raises: [], tags: [].}
- Converts 32-bit integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. Source Edit
proc htons(x: int16): int16 {...}{.raises: [], tags: [].}
- Converts 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. Source Edit
proc socket(domain: Domain = AF_INET; typ: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP; buffered = true): Socket {...}{.raises: [], tags: [].}
- Creates a new socket; returns InvalidSocket if an error occurs. Source Edit
proc raiseSocketError(socket: Socket; err: int = -1; async = false) {...}{.raises: [OSError], tags: [].}
-
Raises proper errors based on return values of recv functions.
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 Edit 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. Source Edit
proc parseIp4(s: string): BiggestInt {...}{.raises: [OverflowError, ValueError], tags: [].}
-
parses an IP version 4 in dotted decimal form like "a.b.c.d".
This is equivalent to inet_ntoa.
Raises ValueError in case of an error.
Source Edit proc bindAddr(socket: Socket; port = Port(0); address = "") {...}{.tags: [ReadIOEffect], raises: [OSError].}
- binds an address/port number to a socket. Use address string in dotted decimal form like "a.b.c.d" or leave "" for any address. Source Edit
proc getSockName(socket: Socket): Port {...}{.raises: [OSError], tags: [].}
- returns the socket's associated port number. Source Edit
proc acceptAddr(server: Socket; client: var Socket; address: var string) {...}{. tags: [ReadIOEffect], 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. If server is non-blocking then this function returns immediately, and if there are no connections queued the returned socket will be InvalidSocket. This function will raise OSError 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.
Warning: When using SSL with non-blocking sockets, it is best to use the acceptAddrSSL procedure as this procedure will most likely block.
Source Edit proc accept(server: Socket; client: var Socket) {...}{.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.
Source Edit proc acceptAddr(server: Socket): tuple[client: Socket, address: string] {...}{.deprecated, tags: [ReadIOEffect], raises: [OSError].}
-
Slightly different version of acceptAddr.
Deprecated since version 0.9.0: Please use the function above.
Source Edit proc accept(server: Socket): Socket {...}{.deprecated, tags: [ReadIOEffect], raises: [OSError].}
- Deprecated since version 0.9.0: Please use the function above. Source Edit
proc close(socket: Socket) {...}{.raises: [], tags: [].}
- closes a socket. Source Edit
proc getServByName(name, proto: string): Servent {...}{.tags: [ReadIOEffect], raises: [OSError].}
-
Searches the database from the beginning and finds the first entry for which the service name specified by name matches the s_name member and the protocol name specified by proto matches the s_proto member.
On posix this will search through the /etc/services file.
Source Edit proc getServByPort(port: Port; proto: string): Servent {...}{.tags: [ReadIOEffect], raises: [OSError].}
-
Searches the database from the beginning and finds the first entry for which the port specified by port matches the s_port member and the protocol name specified by proto matches the s_proto member.
On posix this will search through the /etc/services file.
Source Edit proc getHostByAddr(ip: string): Hostent {...}{.tags: [ReadIOEffect], raises: [OSError].}
- This function will lookup the hostname of an IP Address. Source Edit
proc getHostByName(name: string): Hostent {...}{.tags: [ReadIOEffect], raises: [OSError].}
- This function will lookup the IP address of a hostname. Source Edit
proc getSockOptInt(socket: Socket; level, optname: int): int {...}{.tags: [ReadIOEffect], raises: [OSError].}
- getsockopt for integer options. Source Edit
proc setSockOptInt(socket: Socket; level, optname, optval: int) {...}{. tags: [WriteIOEffect], raises: [OSError].}
- setsockopt for integer options. Source Edit
proc getSockOpt(socket: Socket; opt: SOBool; level = SOL_SOCKET): bool {...}{. tags: [ReadIOEffect], raises: [OSError].}
- Retrieves option opt as a boolean value. Source Edit
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 Edit
proc connect(socket: Socket; address: string; port = Port(0); af: Domain = AF_INET) {...}{. 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 Edit proc connectAsync(socket: Socket; name: string; port = Port(0); af: Domain = AF_INET) {...}{. tags: [ReadIOEffect], raises: [OSError].}
-
A variant of connect for non-blocking sockets.
This procedure will immediately return, it will not block until a connection is made. It is up to the caller to make sure the connection has been established by checking (using select) whether the socket is writeable.
Note: For SSL sockets, the handshake procedure must be called whenever the socket successfully connects to a server.
Source Edit proc hasDataBuffered(s: Socket): bool {...}{.raises: [], tags: [].}
- Determines whether a socket has data buffered. Source Edit
proc select(readfds, writefds, exceptfds: var seq[Socket]; timeout = 500): int {...}{. tags: [ReadIOEffect], raises: [].}
-
Traditional select function. This function will return the number of sockets that are ready to be read from, written to, or which have errors. If there are none; 0 is returned. Timeout is in milliseconds and -1 can be specified for no timeout.
Sockets which are not ready for reading, writing or which don't have errors waiting on them are removed from the readfds, writefds, exceptfds sequences respectively.
Source Edit proc select(readfds, writefds: var seq[Socket]; timeout = 500): int {...}{. tags: [ReadIOEffect], raises: [].}
- Variant of select with only a read and write list. Source Edit
proc selectWrite(writefds: var seq[Socket]; timeout = 500): int {...}{.tags: [ReadIOEffect], raises: [].}
-
When a socket in writefds is ready to be written to then a non-zero value will be returned specifying the count of the sockets which can be written to. The sockets which cannot be written to will also be removed from writefds.
timeout is specified in milliseconds and -1 can be specified for an unlimited time.
Source Edit proc select(readfds: var seq[Socket]; timeout = 500): int {...}{.raises: [], tags: [].}
- variant of select with a read list only Source Edit
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 Edit 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 Edit
proc recv(socket: Socket; data: var string; size: int; timeout = -1): 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 OSError 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.
Source Edit proc recvAsync(socket: Socket; data: var string; size: int): int {...}{.raises: [OSError], tags: [ReadIOEffect].}
-
Async version of recv.
When socket is non-blocking and no data is available on the socket, -1 will be returned and data will be "".
Note: data must be initialised.
Source Edit proc recvLine(socket: Socket; line: var TaintedString; timeout = -1): bool {...}{. tags: [ReadIOEffect, TimeEffect], deprecated, raises: [TimeoutError, OSError].}
-
Receive a line of data from socket.
If a full line is received \r\L is not added to line, however if solely \r\L is received then line will be set to it.
True is returned if data is available. False suggests an error, OSError exceptions are not raised and False is simply returned instead.
If the socket is disconnected, line will be set to "" and True will be returned.
A timeout can be specified in milliseconds, if data is not received within the specified time an ETimeout exception will be raised.
Deprecated since version 0.9.2: This function has been deprecated in favour of readLine.
Source Edit proc readLine(socket: Socket; line: var TaintedString; timeout = -1) {...}{. 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 OSError 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.
Source Edit proc recvLineAsync(socket: Socket; line: var TaintedString): RecvLineResult {...}{. tags: [ReadIOEffect], deprecated, raises: [].}
-
Similar to recvLine but designed for non-blocking sockets.
The values of the returned enum should be pretty self explanatory:
- If a full line has been retrieved; RecvFullLine is returned.
- If some data has been retrieved; RecvPartialLine is returned.
- If the socket has been disconnected; RecvDisconnected is returned.
- If call to recv failed; RecvFail is returned.
Deprecated since version 0.9.2: This function has been deprecated in favour of readLineAsync.
Source Edit proc readLineAsync(socket: Socket; line: var TaintedString): ReadLineResult {...}{. tags: [ReadIOEffect], raises: [OSError].}
-
Similar to recvLine but designed for non-blocking sockets.
The values of the returned enum should be pretty self explanatory:
Source Edit- If a full line has been retrieved; ReadFullLine is returned.
- If some data has been retrieved; ReadPartialLine is returned.
- If the socket has been disconnected; ReadDisconnected is returned.
- If no data could be retrieved; ReadNone is returned.
- If call to recv failed; an OSError exception is raised.
proc recv(socket: Socket): TaintedString {...}{.tags: [ReadIOEffect], deprecated, raises: [OSError].}
-
receives all the available data from the socket. Socket errors will result in an OSError error. If socket is not a connectionless socket and socket is not connected "" will be returned.
Deprecated since version 0.9.2: This function is not safe for use.
Source Edit proc recvTimeout(socket: Socket; timeout: int): TaintedString {...}{.tags: [ReadIOEffect], deprecated, raises: [TimeoutError, OSError].}
-
overloaded variant to support a timeout parameter, the timeout parameter specifies the amount of milliseconds to wait for data on the socket.
Deprecated since version 0.9.2: This function is not safe for use.
Source Edit proc recvAsync(socket: Socket; s: var TaintedString): bool {...}{.tags: [ReadIOEffect], deprecated, raises: [OSError].}
-
receives all the data from a non-blocking socket. If socket is non-blocking and there are no messages available, False will be returned. Other socket errors will result in an OSError error. If socket is not a connectionless socket and socket is not connected s will be set to "".
Deprecated since version 0.9.2: This function is not safe for use.
Source Edit proc recvFrom(socket: Socket; data: var string; length: int; address: var string; port: var Port; flags = 0'i32): int {...}{.tags: [ReadIOEffect], raises: [].}
-
Receives data from socket. This function should normally be used with connection-less sockets (UDP sockets).
If an error occurs the return value will be -1. 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 Edit proc recvFromAsync(socket: Socket; data: var string; length: int; address: var string; port: var Port; flags = 0'i32): bool {...}{.tags: [ReadIOEffect], raises: [OSError].}
-
Variant of recvFrom for non-blocking sockets. Unlike recvFrom, this function will raise an OSError error whenever a socket error occurs.
If there is no data to be read from the socket False will be returned.
Source Edit proc skip(socket: Socket) {...}{.tags: [ReadIOEffect], deprecated, raises: [Exception].}
-
skips all the data that is pending for the socket
Deprecated since version 0.9.2: This function is not safe for use.
Source Edit 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 Edit proc send(socket: Socket; data: pointer; size: int): int {...}{.tags: [WriteIOEffect], raises: [].}
- sends data to a socket. Source Edit
proc send(socket: Socket; data: string) {...}{.tags: [WriteIOEffect], raises: [ValueError, OSError].}
- sends data to a socket. Source Edit
proc sendAsync(socket: Socket; data: string): int {...}{.tags: [WriteIOEffect], raises: [OSError].}
-
sends data to a non-blocking socket. Returns 0 if no data could be sent, if data has been sent returns the amount of bytes of data that was successfully sent. This number may not always be the length of data but typically is.
An OSError (or SslError if socket is an SSL socket) exception is raised if an error occurs.
Source Edit proc trySend(socket: Socket; data: string): bool {...}{.tags: [WriteIOEffect], raises: [].}
- safe alternative to send. Does not raise an OSError when an error occurs, and instead returns false on failure. Source Edit
proc sendTo(socket: Socket; address: string; port: Port; data: pointer; size: int; af: Domain = AF_INET; flags = 0'i32): int {...}{.tags: [WriteIOEffect], raises: [OSError].}
-
low-level sendTo proc. 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: This proc is not available for SSL sockets.
Source Edit proc sendTo(socket: Socket; address: string; port: Port; data: string): int {...}{. tags: [WriteIOEffect], raises: [OSError].}
- Friendlier version of the low-level sendTo. Source Edit
proc setBlocking(s: Socket; blocking: bool) {...}{.tags: [], gcsafe, raises: [OSError].}
- Sets blocking mode on socket Source Edit
proc connect(socket: Socket; address: string; port = Port(0); timeout: int; af: Domain = AF_INET) {...}{.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 Edit proc isSSL(socket: Socket): bool {...}{.raises: [], tags: [].}
- Determines whether socket is a SSL socket. Source Edit
proc getFD(socket: Socket): SocketHandle {...}{.raises: [], tags: [].}
- Returns the socket's file descriptor Source Edit
proc isBlocking(socket: Socket): bool {...}{.raises: [], tags: [].}
- Determines whether socket is blocking. Source Edit