std.socket

Socket primitives. Example: See listener.d and htmlget.d

License

Boost License 1.0.

Authors

Christopher E. Miller, David Nadlinger, Vladimir Panteleev

Source: std/socket.d

Module Initializers 1

shared static this()

Module Deinitializers 1

shared static ~this()

Types 30

classSocketException : Exception

Base exception thrown by std.socket.

Socket exception representing network errors reported by the operating system.

Fields
int errorCode
Constructors
this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null, int err = _lasterr(), string function(int) @trusted errorFormatter = & formatSocketError)
this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__, int err = _lasterr(), string function(int) @trusted errorFormatter = & formatSocketError)
this(string msg, int err, string function(int) @trusted errorFormatter = & formatSocketError, string file = __FILE__, size_t line = __LINE__, Throwable next = null)

Socket exception representing invalid parameters specified by user code.

Socket exception representing attempts to use network capabilities not available on the current system.

enumAddressFamily : ushort

The communication domain used to resolve an address.

UNSPEC = AF_UNSPECUnspecified address family
UNIX = AF_UNIXLocal communication (Unix socket)
INET = AF_INETInternet Protocol version 4
IPX = AF_IPXNovell IPX
APPLETALK = AF_APPLETALKAppleTalk
INET6 = AF_INET6Internet Protocol version 6
enumSocketType : int

Communication semantics

STREAM = SOCK_STREAMSequenced, reliable, two-way communication-based byte streams
DGRAM = SOCK_DGRAMConnectionless, unreliable datagrams with a fixed maximum length; data may be lost or arrive out of order
RAW = SOCK_RAWRaw protocol access
RDM = SOCK_RDMReliably-delivered message datagrams
SEQPACKET = SOCK_SEQPACKETSequenced, reliable, two-way connection-based datagrams with a fixed maximum length
enumProtocolType : int

Protocol

IP = IPPROTO_IPInternet Protocol version 4
ICMP = IPPROTO_ICMPInternet Control Message Protocol
IGMP = IPPROTO_IGMPInternet Group Management Protocol
GGP = IPPROTO_GGPGateway to Gateway Protocol
TCP = IPPROTO_TCPTransmission Control Protocol
PUP = IPPROTO_PUPPARC Universal Packet Protocol
UDP = IPPROTO_UDPUser Datagram Protocol
IDP = IPPROTO_IDPXerox NS protocol
RAW = IPPROTO_RAWRaw IP packets
IPV6 = IPPROTO_IPV6Internet Protocol version 6

Class for retrieving protocol information.

Example:

auto proto = new Protocol;
writeln("About protocol TCP:");
if (proto.getProtocolByType(ProtocolType.TCP))
{
   writefln("  Name: %s", proto.name);
   foreach (string s; proto.aliases)
        writefln("  Alias: %s", s);
}
else
   writeln("  No information found");

Fields
ProtocolType typeThese members are populated when one of the following functions are called successfully:
string name
string[] aliases
Methods
void populate(protoent * proto) @system pure nothrow
bool getProtocolByName(scope const(char)[] name) @trusted nothrowReturns: false on failure
bool getProtocolByType(ProtocolType type) @trusted nothrowReturns: false on failure
classService

Class for retrieving service information.

Example:

auto serv = new Service;
writeln("About service epmap:");
if (serv.getServiceByName("epmap", "tcp"))
{
   writefln("  Service: %s", serv.name);
   writefln("  Port: %d", serv.port);
   writefln("  Protocol: %s", serv.protocolName);
   foreach (string s; serv.aliases)
        writefln("  Alias: %s", s);
}
else
   writefln("  No service for epmap.");

Fields
string nameThese members are populated when one of the following functions are called successfully:
string[] aliases
ushort port
string protocolName
Methods
void populate(servent * serv) @system pure nothrow
bool getServiceByName(scope const(char)[] name, scope const(char)[] protocolName = null) @trusted nothrowIf a protocol name is omitted, any protocol will be matched. Returns: false on failure.
bool getServiceByPort(ushort port, scope const(char)[] protocolName = null) @trusted nothrowditto

Class for exceptions thrown from an InternetHost.

Class for resolving IPv4 addresses.

Consider using getAddress, parseAddress and Address methods instead of using this class directly.

Fields
string nameThese members are populated when one of the following functions are called successfully:
string[] aliases
uint[] addrList
Methods
void validHostent(in hostent * he)
void populate(hostent * he) @system pure nothrow
private bool getHostNoSync(string opMixin, T)(T param) @system
bool getHostByName(scope const(char)[] name) @trustedResolve host name. Returns: false if unable to resolve.
bool getHostByAddr(uint addr) @trustedResolve IPv4 address number.
bool getHostByAddr(scope const(char)[] addr) @trustedSame as previous, but addr is an IPv4 address string in the dotted-decimal form a.b.c.d. Returns: false if unable to resolve.

Holds information about a socket _address retrieved by getAddressInfo.

Fields
ProtocolType protocol
Address address
string canonicalName

A subset of flags supported on all platforms with getaddrinfo. Specifies option flags for getAddressInfo.

PASSIVE = AI_PASSIVEThe resulting addresses will be used in a call to `Socket.bind`.
CANONNAME = AI_CANONNAMEThe canonical name is returned in `canonicalName` member in the first `AddressInfo`.
NUMERICHOST = AI_NUMERICHOSTThe `node` parameter passed to `getAddressInfo` must be a numeric string. This will suppress any potentially lengthy network host address lookups.

Class for exceptions thrown from an Address.

classAddress

Abstract class for representing a socket address.

Example:

writeln("About www.google.com port 80:");
try
{
   Address[] addresses = getAddress("www.google.com", 80);
   writefln("  %d addresses found.", addresses.length);
   foreach (int i, Address a; addresses)
   {
       writefln("  Address %d:", i+1);
       writefln("    IP address: %s", a.toAddrString());
       writefln("    Hostname: %s", a.toHostNameString());
       writefln("    Port: %s", a.toPortString());
       writefln("    Service name: %s",
           a.toServiceNameString());
   }
}
catch (SocketException e)
   writefln("  Lookup error: %s", e.msg);

Methods
sockaddr * name() @property pure nothrow @nogcReturns pointer to underlying `sockaddr` structure.
const(sockaddr) * name() @property const pure nothrow @nogc
socklen_t nameLen() @property const pure nothrow @nogcReturns actual size of underlying `sockaddr` structure.
void setNameLen(socklen_t len)
AddressFamily addressFamily() @property const pure nothrow @nogcFamily of this address.
private string toHostString(bool numeric) @trusted const
private string toServiceString(bool numeric) @trusted const
string toAddrString() constAttempts to retrieve the host address as a human-readable string.
string toHostNameString() constAttempts to retrieve the host name as a fully qualified domain name.
string toPortString() constAttempts to retrieve the numeric port number as a string.
string toServiceNameString() constAttempts to retrieve the service name as a string.
string toString() constHuman readable string representing this address.

Encapsulates an unknown socket address.

Fields
sockaddr sa
Methods
sockaddr * name() @property return
const(sockaddr) * name() @property const return
socklen_t nameLen() @property const

Encapsulates a reference to an arbitrary socket address.

Fields
sockaddr * sa
socklen_t len
Methods
sockaddr * name() @property
const(sockaddr) * name() @property const
socklen_t nameLen() @property const
Constructors
this(sockaddr * sa, socklen_t len)Constructs an `Address` with a reference to the specified `sockaddr`.
this(const(sockaddr) * sa, socklen_t len)Constructs an `Address` with a copy of the specified `sockaddr`.

Encapsulates an IPv4 (Internet Protocol version 4) socket address.

Consider using getAddress, parseAddress and Address methods instead of using this class directly.

Fields
sockaddr_in sin
uint ADDR_ANY
uint ADDR_NONE
ushort PORT_ANY
Methods
sockaddr * name() @property return
const(sockaddr) * name() @property const return
socklen_t nameLen() @property const
ushort port() @property const pure nothrow @nogcReturns the IPv4 port number (in host byte order).
uint addr() @property const pure nothrow @nogcReturns the IPv4 address number (in host byte order).
string toAddrString() @trusted constHuman readable string representing the IPv4 address in dotted-decimal form.
string toPortString() constHuman readable string representing the IPv4 port.
string toHostNameString() constAttempts to retrieve the host name as a fully qualified domain name.
bool opEquals(Object o) constProvides support for comparing equality with another InternetAddress of the same type. Returns: true if the InternetAddresses share the same address and port number.
uint parse(scope const(char)[] addr) @trusted nothrowParse an IPv4 address string in the dotted-decimal form a.b.c.d and return the number. Returns: If the string is not a legitimate IPv4 address, `ADDR_NONE` is returned.
string addrToString(uint addr) @trusted nothrowConvert an IPv4 address number in host byte order to a human readable string representing the IPv4 address in dotted-decimal form.
Constructors
this(scope const(char)[] addr, ushort port)Construct a new `InternetAddress`. Params: addr = an IPv4 address string in the dotted-decimal form a.b.c.d, or a host name which will be resolved using an `InternetHost` object. port = port number...
this(uint addr, ushort port)Construct a new `InternetAddress`. Params: addr = (optional) an IPv4 address in host byte order, may be `ADDRANY`. port = port number, may be `PORTANY`.
this(ushort port)ditto
this(sockaddr_in addr)Construct a new `InternetAddress`. Params: addr = A sockaddr_in as obtained from lower-level API calls such as getifaddrs.

Encapsulates an IPv6 (Internet Protocol version 6) socket address.

Consider using getAddress, parseAddress and Address methods instead of using this class directly.

Fields
sockaddr_in6 sin6
ushort PORT_ANYAny IPv6 port number.
Methods
sockaddr * name() @property return
const(sockaddr) * name() @property const return
socklen_t nameLen() @property const
const(ubyte)[16] ADDR_ANY() @property ref pure nothrow @nogcAny IPv6 host address.
ushort port() @property const pure nothrow @nogcReturns the IPv6 port number.
ubyte[16] addr() @property const pure nothrow @nogcReturns the IPv6 address.
ubyte[16] parse(scope const(char)[] addr) @trustedParse an IPv6 host address string as described in RFC 2373, and return the address. Throws: `SocketException` on error.
Constructors
this(scope const(char)[] addr, scope const(char)[] service = null)Construct a new `Internet6Address`. Params: addr = an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved using `getAddressInfo`. service = (optiona...
this(scope const(char)[] addr, ushort port)Construct a new `Internet6Address`. Params: addr = an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved using `getAddressInfo`. port = port number, m...
this(ubyte[16] addr, ushort port)Construct a new `Internet6Address`. Params: addr = (optional) an IPv6 host address in host byte order, or `ADDRANY`. port = port number, may be `PORTANY`.
this(ushort port)ditto
this(sockaddr_in6 addr)Construct a new `Internet6Address`. Params: addr = A sockaddr_in6 as obtained from lower-level API calls such as getifaddrs.

Exception thrown by Socket.accept.

enumSocketShutdown : int

How a socket is shutdown:

RECEIVE = SD_RECEIVEsocket receives are disallowed
SEND = SD_SENDsocket sends are disallowed
BOTH = SD_BOTHboth RECEIVE and SEND
enumSocketFlags : int

Socket flags that may be OR'ed together:

NONE = 0no flags specified
OOB = MSG_OOBout-of-band stream data
PEEK = MSG_PEEKpeek at incoming data without removing it from the queue, only for receiving
DONTROUTE = MSG_DONTROUTEdata should not be subject to routing; this flag may be ignored. Only for sending
structTimeVal

Duration timeout value.

Fields
_ctimeval ctimeval
Methods
inout(tv_sec_t) seconds() pure nothrow @nogc @property ref inout returnNumber of seconds.
inout(tv_usec_t) microseconds() pure nothrow @nogc @property ref inout returnNumber of additional microseconds.

A collection of sockets for use with Socket.select.

SocketSet wraps the platform fd_set type. However, unlike fd_set, SocketSet is not statically limited to FD_SETSIZE or any other limit, and grows as needed.

Methods
void reset() pure nothrow @nogcReset the `SocketSet` so that there are 0 `Socket`s in the collection.
void add(socket_t s) @trusted pure nothrow
void add(Socket s) pure nothrowAdd a `Socket` to the collection. The socket must not already be in the collection.
void remove(socket_t s) pure nothrow
void remove(Socket s) pure nothrowRemove this `Socket` from the collection. Does nothing if the socket is not in the collection already.
int isSet(socket_t s) const pure nothrow @nogc
int isSet(Socket s) const pure nothrow @nogcReturn nonzero if this `Socket` is in the collection.
uint max() @property const pure nothrow @nogcReturns: The current capacity of this `SocketSet`. The exact meaning of the return value varies from platform to platform.
fd_set * toFd_set() @trusted pure nothrow @nogc
int selectn() const pure nothrow @nogc
Constructors
this(size_t size = FD_SETSIZE)Create a SocketSet with a specific initial capacity (defaults to `FD_SETSIZE`, the system's default capacity).

The level at which a socket option is defined:

SOCKET = SOL_SOCKETSocket level
IP = ProtocolType.IPInternet Protocol version 4 level
ICMP = ProtocolType.ICMPInternet Control Message Protocol level
IGMP = ProtocolType.IGMPInternet Group Management Protocol level
GGP = ProtocolType.GGPGateway to Gateway Protocol level
TCP = ProtocolType.TCPTransmission Control Protocol level
PUP = ProtocolType.PUPPARC Universal Packet Protocol level
UDP = ProtocolType.UDPUser Datagram Protocol level
IDP = ProtocolType.IDPXerox NS protocol level
RAW = ProtocolType.RAWRaw IP packet level
IPV6 = ProtocolType.IPV6Internet Protocol version 6 level
structLinger

_Linger information for use with SocketOption.LINGER.

Fields
_clinger clinger
Methods
inout(l_onoff_t) on() pure nothrow @nogc @property ref inout returnNonzero for on.
inout(l_linger_t) time() pure nothrow @nogc @property ref inout returnLinger time.
enumSocketOption : int

Specifies a socket option:

DEBUG = SO_DEBUGRecord debugging information
BROADCAST = SO_BROADCASTAllow transmission of broadcast messages
REUSEADDR = SO_REUSEADDRAllow local reuse of address
REUSEPORT = SO_REUSEPORTAllow local reuse of port
LINGER = SO_LINGERLinger on close if unsent data is present
OOBINLINE = SO_OOBINLINEReceive out-of-band data in band
SNDBUF = SO_SNDBUFSend buffer size
RCVBUF = SO_RCVBUFReceive buffer size
DONTROUTE = SO_DONTROUTEDo not route
SNDTIMEO = SO_SNDTIMEOSend timeout
RCVTIMEO = SO_RCVTIMEOReceive timeout
ERROR = SO_ERRORRetrieve and clear error status
KEEPALIVE = SO_KEEPALIVEEnable keep-alive packets
ACCEPTCONN = SO_ACCEPTCONNListen
RCVLOWAT = SO_RCVLOWATMinimum number of input bytes to process
SNDLOWAT = SO_SNDLOWATMinimum number of output bytes to process
TYPE = SO_TYPESocket type
TCP_NODELAY = .TCP_NODELAYDisable the Nagle algorithm for send coalescing
IPV6_UNICAST_HOPS = .IPV6_UNICAST_HOPSIP unicast hop limit
IPV6_MULTICAST_IF = .IPV6_MULTICAST_IFIP multicast interface
IPV6_MULTICAST_LOOP = .IPV6_MULTICAST_LOOPIP multicast loopback
IPV6_MULTICAST_HOPS = .IPV6_MULTICAST_HOPSIP multicast hops
IPV6_JOIN_GROUP = .IPV6_JOIN_GROUPAdd an IP group membership
IPV6_LEAVE_GROUP = .IPV6_LEAVE_GROUPDrop an IP group membership
IPV6_V6ONLY = .IPV6_V6ONLYTreat wildcard bind as AF_INET6-only
classSocket

Class that creates a network communication endpoint using the Berkeley sockets interface.

Fields
socket_t sock
500 WINSOCK_TIMEOUT_SKEW
int ERRORSend or receive error code. See `wouldHaveBlocked`, `lastSocketError` and `Socket.getErrorText` for obtaining more information about the error.
Methods
void setSock(socket_t handle)
socket_t handle() @property const pure nothrow @nogcGet underlying socket handle.
socket_t release() @property pure nothrow @nogcReleases the underlying socket handle from the Socket object. Once it is released, you cannot use the Socket object's methods anymore. This also means the Socket destructor will no longer close the...
bool blocking() @property @trusted const nothrow @nogcGet/set socket's blocking flag.
void blocking(bool byes) @property @trustedditto
AddressFamily addressFamily() @propertyGet the socket's address family.
bool isAlive() @property @trusted constProperty that indicates if this is a valid, alive socket.
void bind(Address addr) @trustedAssociate a local address with this socket.
void connect(Address to) @trustedEstablish a connection. If the socket is blocking, connect waits for the connection to be made. If the socket is nonblocking, connect returns immediately and the connection attempt is still in prog...
void listen(int backlog) @trustedListen for an incoming connection. `bind` must be called before you can `listen`. The `backlog` is a request of how many pending incoming connections are queued until `accept`ed.
Socket accepting() pure nothrowCalled by `accept` when a new `Socket` must be created for a new connection. To use a derived class, override this method and return an instance of your class. The returned `Socket`'s handle must n...
Socket accept() @trustedAccept an incoming connection. If the socket is blocking, `accept` waits for a connection request. Throws `SocketAcceptException` if unable to accept. See `accepting` for use with derived classes.
void shutdown(SocketShutdown how) @trusted nothrow @nogcDisables sends and/or receives.
private void _close(socket_t sock) @system nothrow @nogc
void close() scope @trusted nothrow @nogcImmediately drop any connections and release socket resources. The `Socket` object is no longer usable after `close`. Calling `shutdown` before `close` is recommended for connection-oriented sockets.
string hostName() @property @trustedReturns: The local machine's host name
Address remoteAddress() @property @trustedRemote endpoint `Address`.
Address localAddress() @property @trustedLocal endpoint `Address`.
private int capToInt(size_t size) nothrow @nogc
ptrdiff_t send(scope const(void)[] buf, SocketFlags flags) @trustedSend data on the connection. If the socket is blocking and there is no buffer space left, `send` waits. Returns: The number of bytes actually sent, or `Socket.ERROR` on failure.
ptrdiff_t send(scope const(void)[] buf)ditto
ptrdiff_t sendTo(scope const(void)[] buf, SocketFlags flags, Address to) @trustedSend data to a specific destination Address. If the destination address is not specified, a connection must have been made and that address is used. If the socket is blocking and there is no buffer...
ptrdiff_t sendTo(scope const(void)[] buf, Address to)ditto
ptrdiff_t sendTo(scope const(void)[] buf, SocketFlags flags) @trustedditto
ptrdiff_t sendTo(scope const(void)[] buf)ditto
ptrdiff_t receive(scope void[] buf, SocketFlags flags) @trustedReceive data on the connection. If the socket is blocking, `receive` waits until there is data to be received. Returns: The number of bytes actually received, `0` if the remote side has closed the ...
ptrdiff_t receive(scope void[] buf)ditto
ptrdiff_t receiveFrom(scope void[] buf, SocketFlags flags, ref Address from) @trustedReceive data and get the remote endpoint `Address`. If the socket is blocking, `receiveFrom` waits until there is data to be received. Returns: The number of bytes actually received, `0` if the rem...
ptrdiff_t receiveFrom(scope void[] buf, ref Address from)ditto
ptrdiff_t receiveFrom(scope void[] buf, SocketFlags flags) @trustedditto
ptrdiff_t receiveFrom(scope void[] buf)ditto
int getOption(SocketOptionLevel level, SocketOption option, scope void[] result) @trustedGet a socket option. Returns: The number of bytes written to `result`. The length, in bytes, of the actual result - very different from getsockopt()
int getOption(SocketOptionLevel level, SocketOption option, out int32_t result) @trustedCommon case of getting integer and boolean options.
int getOption(SocketOptionLevel level, SocketOption option, out Linger result) @trustedGet the linger option.
void getOption(SocketOptionLevel level, SocketOption option, out Duration result) @trustedGet a timeout (duration) option.
void setOption(SocketOptionLevel level, SocketOption option, scope void[] value) @trustedSet a socket option.
void setOption(SocketOptionLevel level, SocketOption option, int32_t value) @trustedCommon case for setting integer and boolean options.
void setOption(SocketOptionLevel level, SocketOption option, Linger value) @trustedSet the linger option.
void setOption(SocketOptionLevel level, SocketOption option, Duration value) @trustedSets a timeout (duration) option, i.e. `SocketOption.SNDTIMEO` or `RCVTIMEO`. Zero indicates no timeout.
string getErrorText()Get a text description of this socket's error status, and clear the socket's error status.
void setKeepAlive(int time, int interval) @trustedEnables TCP keep-alive with the specified parameters.
int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, Duration timeout) @trustedWait for a socket to change status. A wait timeout of Duration or `TimeVal`, may be specified; if a timeout is not specified or the `TimeVal` is `null`, the maximum timeout is used. The `TimeVal` t...
int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError)ditto
int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, TimeVal * timeout) @trustedDitto
Address createAddress() pure nothrowCan be overridden to support other addresses. Returns: A new `Address` object for the current address family.
Constructors
this(AddressFamily af, SocketType type, ProtocolType protocol)Create a blocking socket. If a single protocol type exists to support this socket type within the address family, the `ProtocolType` may be omitted.
this(AddressFamily af, SocketType type, scope const(char)[] protocolName)ditto
this(const scope AddressInfo info)Create a blocking socket using the parameters from the specified `AddressInfo` structure.
this(socket_t sock, AddressFamily af)Use an existing socket handle.
Destructors

Shortcut class for a TCP Socket.

Constructors
this(AddressFamily family)Constructs a blocking TCP Socket.
this()Constructs a blocking IPv4 TCP Socket.
this(Address connectTo)Constructs a blocking TCP Socket and connects to the given `Address`.

Shortcut class for a UDP Socket.

Constructors
this(AddressFamily family)Constructs a blocking UDP Socket.
this()Constructs a blocking IPv4 UDP Socket.

Functions 12

fnstring formatSocketError(int err) @trusted
fnstring lastSocketError() @propertyReturns the error message of the most recently encountered network error.
fnbool wouldHaveBlocked() nothrow @nogcReturns: `true` if the last socket operation failed because the socket was in non-blocking mode and the operation would have blocked, or if the socket is in blocking mode and set a `SNDTIMEO` or `R...
private fnstring formatGaiError(int err) @trustedOn POSIX, getaddrinfo uses its own error codes, and thus has its own formatting function.
fnAddressInfo[] getAddressInfo(T...)(scope const(char)[] node, scope T options)Provides protocol-independent translation from host names to socket addresses. If advanced functionality is not required, consider using `getAddress` for compatibility with older systems.
private fnAddressInfo[] getAddressInfoImpl(scope const(char)[] node, scope const(char)[] service, addrinfo * hints) @system
private fnushort serviceToPort(scope const(char)[] service)
fnAddress[] getAddress(scope const(char)[] hostname, scope const(char)[] service = null)Provides protocol-independent translation from host names to socket addresses. Uses `getAddressInfo` if the current system supports it, and `InternetHost` otherwise.
fnAddress[] getAddress(scope const(char)[] hostname, ushort port)ditto
fnAddress parseAddress(scope const(char)[] hostaddr, scope const(char)[] service = null)Provides protocol-independent parsing of network addresses. Does not attempt name resolution. Uses `getAddressInfo` with `AddressInfoFlags.NUMERICHOST` if the current system supports it, and `Inter...
fnAddress parseAddress(scope const(char)[] hostaddr, ushort port)ditto
fnSocket[2] socketPair() @trustedCreates a pair of connected sockets.

Variables 3

vartypeof(& getnameinfo) getnameinfoPointer
vartypeof(& getaddrinfo) getaddrinfoPointer
vartypeof(& freeaddrinfo) freeaddrinfoPointer