Socket primitives.
class
SocketException:
object.Exception;
Base exception thrown bystd.socket.
@property @safe string
lastSocketError();
Returns the error message of the most recently encountered network error.
class
SocketOSException:
std.socket.SocketException;
Socket exception representing network errors reported by the operating system.
Platform-specific error code.
@safe this(string
msg, string
file = __FILE__, size_t
line = __LINE__, Throwable
next = null, int
err = _lasterr(), string function(int) @trusted
errorFormatter = &formatSocketError);
@safe this(string
msg, Throwable
next, string
file = __FILE__, size_t
line = __LINE__, int
err = _lasterr(), string function(int) @trusted
errorFormatter = &formatSocketError);
@safe this(string
msg, int
err, string function(int) @trusted
errorFormatter = &formatSocketError, string
file = __FILE__, size_t
line = __LINE__, Throwable
next = null);
class
SocketParameterException:
std.socket.SocketException;
Socket exception representing invalid parameters specified by user code.
class
SocketFeatureException:
std.socket.SocketException;
Socket exception representing attempts to use network capabilities not available on the current system.
nothrow @nogc @safe bool
wouldHaveBlocked();
Returns: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 aSNDTIMEO orRCVTIMEO, and the operation timed out.
enum
AddressFamily: ushort;
The communication domain used to resolve an address.
Unspecified address family
Local communication (Unix socket)
Internet Protocol version 4
Novell IPX
AppleTalk
Internet Protocol version 6
Communication semantics
Sequenced, reliable, two-way communication-based byte streams
Connectionless, unreliable datagrams with a fixed maximum length; data may be lost or arrive out of order
Raw protocol access
Reliably-delivered message datagrams
Sequenced, reliable, two-way connection-based datagrams with a fixed maximum length
Protocol
Internet Protocol version 4
Internet Control Message Protocol
Internet Group Management Protocol
Gateway to Gateway Protocol
Transmission Control Protocol
PARC Universal Packet Protocol
User Datagram Protocol
Xerox NS protocol
Raw IP packets
Internet Protocol version 6
Class for retrieving protocol information.
Example
auto proto =newProtocol;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");ProtocolType
type;
string
name;
string[]
aliases;
These members are populated when one of the following functions are called successfully:
nothrow @trusted bool
getProtocolByName(scope const(char)[]
name);
nothrow @trusted bool
getProtocolByType(ProtocolType
type);
Class for retrieving service information.
Example
auto serv =newService;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.");string
name;
string[]
aliases;
ushort
port;
string
protocolName;
These members are populated when one of the following functions are called successfully:
nothrow @trusted bool
getServiceByName(scope const(char)[]
name, scope const(char)[]
protocolName = null);
nothrow @trusted bool
getServiceByPort(ushort
port, scope const(char)[]
protocolName = null);
If a protocol name is omitted, any protocol will be matched.
Returns:false on failure.
class
HostException:
std.socket.SocketOSException;
Class for exceptions thrown from anInternetHost.
Class for resolving IPv4 addresses.
Consider usinggetAddress,parseAddress andAddress methods instead of using this class directly.
Examples:InternetHost ih =newInternetHost;ih.getHostByAddr(0x7F_00_00_01);writeln(ih.addrList[0]);// 0x7F_00_00_01ih.getHostByAddr("127.0.0.1");writeln(ih.addrList[0]);// 0x7F_00_00_01if (!ih.getHostByName("www.digitalmars.com"))return;// don't fail if not connected to internetassert(ih.addrList.length);InternetAddress ia =new InternetAddress(ih.addrList[0], InternetAddress.PORT_ANY);assert(ih.name =="www.digitalmars.com" || ih.name =="digitalmars.com", ih.name);/* The following assert randomly fails in the test suite. * https://issues.dlang.org/show_bug.cgi?id=22791 * So just ignore it when it fails. *///assert(ih.getHostByAddr(ih.addrList[0]));if (ih.getHostByAddr(ih.addrList[0])){ string getHostNameFromInt = ih.name.dup;// This randomly fails in the compiler test suite//assert(ih.getHostByAddr(ia.toAddrString()));if (ih.getHostByAddr(ia.toAddrString())) { string getHostNameFromStr = ih.name.dup; writeln(getHostNameFromInt);// getHostNameFromStr }} string
name;
string[]
aliases;
uint[]
addrList;
These members are populated when one of the following functions are called successfully:
@trusted bool
getHostByName(scope const(char)[]
name);
Resolve host name.
Returns:false if unable to resolve.
@trusted bool
getHostByAddr(uint
addr);
Resolve IPv4 address number.
Parameters:uintaddr | The IPv4 address to resolve, in host byte order. |
Returns:false if unable to resolve.
@trusted bool
getHostByAddr(scope const(char)[]
addr);
Same as previous, but addr is an IPv4 address string in the dotted-decimal forma.b.c.d.
Returns:false if unable to resolve.
Holds information about a socket address retrieved bygetAddressInfo.
Address family
Socket type
Protocol
Socket address
Canonical name, whenAddressInfoFlags.CANONNAME is used.
enum
AddressInfoFlags: int;
A subset of flags supported on all platforms with getaddrinfo. Specifies option flags forgetAddressInfo.
The resulting addresses will be used in a call toSocket.bind.
The canonical name is returned incanonicalName member in the firstAddressInfo.
Thenode parameter passed togetAddressInfo must be a numeric string. This will suppress any potentially lengthy network host address lookups.
AddressInfo[]
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 usinggetAddress for compatibility with older systems.
Returns:Array with oneAddressInfo per socket address.
Throws:SocketOSException on failure, orSocketFeatureException if this functionality is not available on the current system.
Parameters:const(char)[]node | string containing host name or numeric address |
Toptions | optional additional parameters, identified by type:- string - service name or port number
- AddressInfoFlags - option flags
- AddressFamily - address family to filter by
- SocketType - socket type to filter by
- ProtocolType - protocol to filter by
|
Example
// Roundtrip DNS resolutionauto results =getAddressInfo("www.digitalmars.com");assert(results[0].address.toHostNameString() =="digitalmars.com");// Canonical nameresults =getAddressInfo("www.digitalmars.com", AddressInfoFlags.CANONNAME);assert(results[0].canonicalName =="digitalmars.com");// IPv6 resolutionresults =getAddressInfo("ipv6.google.com");assert(results[0].family == AddressFamily.INET6);// Multihomed resolutionresults =getAddressInfo("google.com");assert(results.length > 1);// Parsing IPv4results =getAddressInfo("127.0.0.1", AddressInfoFlags.NUMERICHOST);assert(results.length && results[0].family == AddressFamily.INET);// Parsing IPv6results =getAddressInfo("::1", AddressInfoFlags.NUMERICHOST);assert(results.length && results[0].family == AddressFamily.INET6);@safe Address[]
getAddress(scope const(char)[]
hostname, scope const(char)[]
service = null);
@safe Address[]
getAddress(scope const(char)[]
hostname, ushort
port);
Provides protocol-independent translation from host names to socket addresses. UsesgetAddressInfo if the current system supports it, andInternetHost otherwise.
Returns:Array with oneAddress instance per socket address.
Throws:SocketOSException on failure.
Example
writeln("Resolving www.digitalmars.com:");try{auto addresses =getAddress("www.digitalmars.com");foreach (address; addresses) writefln(" IP: %s", address.toAddrString());}catch (SocketException e) writefln(" Lookup failed: %s", e.msg);@safe Address
parseAddress(scope const(char)[]
hostaddr, scope const(char)[]
service = null);
@safe Address
parseAddress(scope const(char)[]
hostaddr, ushort
port);
Provides protocol-independent parsing of network addresses. Does not attempt name resolution. UsesgetAddressInfo withAddressInfoFlags.NUMERICHOST if the current system supports it, andInternetAddress otherwise.
Returns:AnAddress instance representing specified address.
Throws:SocketException on failure.
Example
writeln("Enter IP address:");string ip = readln().chomp();try{ Address address =parseAddress(ip); writefln("Looking up reverse of %s:", address.toAddrString());try { string reverse = address.toHostNameString();if (reverse) writefln(" Reverse name: %s", reverse);else writeln(" Reverse hostname not found."); }catch (SocketException e) writefln(" Lookup error: %s", e.msg);}catch (SocketException e){ writefln(" %s is not a valid IP address: %s", ip, e.msg);}class
AddressException:
std.socket.SocketOSException;
Class for exceptions thrown from anAddress.
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);abstract pure nothrow @nogc @property @safe sockaddr*
name();
abstract pure nothrow @nogc @property @safe const(sockaddr)*
name() const;
Returns pointer to underlyingsockaddr structure.
abstract pure nothrow @nogc @property @safe socklen_t
nameLen() const;
Returns actual size of underlyingsockaddr structure.
pure nothrow @nogc @property @safe AddressFamily
addressFamily() const;
Family of this address.
@safe string
toAddrString() const;
Attempts to retrieve the host address as a human-readable string.
Throws:AddressException on failure, orSocketFeatureException if address retrieval for this address family is not available on the current system.
@safe string
toHostNameString() const;
Attempts to retrieve the host name as a fully qualified domain name.
Returns:The FQDN corresponding to thisAddress, ornull if the host name did not resolve.
Throws:AddressException on error, orSocketFeatureException if host name lookup for this address family is not available on the current system.
@safe string
toPortString() const;
Attempts to retrieve the numeric port number as a string.
Throws:AddressException on failure, orSocketFeatureException if port number retrieval for this address family is not available on the current system.
@safe string
toServiceNameString() const;
Attempts to retrieve the service name as a string.
Throws:AddressException on failure, orSocketFeatureException if service name lookup for this address family is not available on the current system.
@safe string
toString() const;
Human readable string representing this address.
class
UnknownAddress:
std.socket.Address;
Encapsulates an unknown socket address.
class
UnknownAddressReference:
std.socket.Address;
Encapsulates a reference to an arbitrary socket address.
pure nothrow @nogc @safe this(sockaddr*
sa, socklen_t
len);
Constructs anAddress with a reference to the specifiedsockaddr.
pure nothrow @system this(const(sockaddr)*
sa, socklen_t
len);
Constructs anAddress with a copy of the specifiedsockaddr.
class
InternetAddress:
std.socket.Address;
Encapsulates an IPv4 (Internet Protocol version 4) socket address.
Consider usinggetAddress,parseAddress andAddress methods instead of using this class directly.
Any IPv4 host address.
An invalid IPv4 host address.
Any IPv4 port number.
pure nothrow @nogc @property @safe ushort
port() const;
Returns the IPv4 port number (in host byte order).
pure nothrow @nogc @property @safe uint
addr() const;
Returns the IPv4 address number (in host byte order).
@safe this(scope const(char)[]
addr, ushort
port);
Construct a newInternetAddress.
Parameters:const(char)[]addr | an IPv4 address string in the dotted-decimal form a.b.c.d, or a host name which will be resolved using anInternetHost object. |
ushortport | port number, may bePORT_ANY. |
pure nothrow @nogc @safe this(uint
addr, ushort
port);
pure nothrow @nogc @safe this(ushort
port);
Construct a newInternetAddress.
Parameters:uintaddr | (optional) an IPv4 address in host byte order, may beADDR_ANY. |
ushortport | port number, may bePORT_ANY. |
pure nothrow @nogc @safe this(sockaddr_in
addr);
Construct a newInternetAddress.
Parameters:sockaddr_inaddr | A sockaddr_in as obtained from lower-level API calls such as getifaddrs. |
@trusted string
toAddrString() const;
Human readable string representing the IPv4 address in dotted-decimal form.
@safe string
toPortString() const;
Human readable string representing the IPv4 port.
@safe string
toHostNameString() const;
Attempts to retrieve the host name as a fully qualified domain name.
Returns:The FQDN corresponding to thisInternetAddress, ornull if the host name did not resolve.
Throws:AddressException on error.
@safe bool
opEquals(Object
o) const;
Provides support for comparing equality with another InternetAddress of the same type.
Returns:true if the InternetAddresses share the same address and port number.
Examples:auto addr1 =new InternetAddress("127.0.0.1", 80);auto addr2 =new InternetAddress("127.0.0.2", 80);writeln(addr1);// addr1assert(addr1 != addr2); static nothrow @trusted uint
parse(scope const(char)[]
addr);
Parse an IPv4 address string in the dotted-decimal forma.b.c.d and return the number.
Returns:If the string is not a legitimate IPv4 address,ADDR_NONE is returned.
static nothrow @trusted string
addrToString(uint
addr);
Convert an IPv4 address number in host byte order to a human readable string representing the IPv4 address in dotted-decimal form.
class
Internet6Address:
std.socket.Address;
Encapsulates an IPv6 (Internet Protocol version 6) socket address.
Consider usinggetAddress,parseAddress andAddress methods instead of using this class directly.
static pure nothrow @nogc @property ref @safe const(ubyte)[16]
ADDR_ANY();
Any IPv6 host address.
Any IPv6 port number.
pure nothrow @nogc @property @safe ushort
port() const;
Returns the IPv6 port number.
pure nothrow @nogc @property @safe ubyte[16]
addr() const;
Returns the IPv6 address.
@trusted this(scope const(char)[]
addr, scope const(char)[]
service = null);
Construct a newInternet6Address.
Parameters:const(char)[]addr | an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved usinggetAddressInfo. |
const(char)[]service | (optional) service name. |
@safe this(scope const(char)[]
addr, ushort
port);
Construct a newInternet6Address.
Parameters:const(char)[]addr | an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved usinggetAddressInfo. |
ushortport | port number, may bePORT_ANY. |
pure nothrow @nogc @safe this(ubyte[16]
addr, ushort
port);
pure nothrow @nogc @safe this(ushort
port);
Construct a newInternet6Address.
Parameters:ubyte[16]addr | (optional) an IPv6 host address in host byte order, orADDR_ANY. |
ushortport | port number, may bePORT_ANY. |
pure nothrow @nogc @safe this(sockaddr_in6
addr);
Construct a newInternet6Address.
Parameters:sockaddr_in6addr | A sockaddr_in6 as obtained from lower-level API calls such as getifaddrs. |
static @trusted ubyte[16]
parse(scope const(char)[]
addr);
Parse an IPv6 host address string as described in RFC 2373, and return the address.
Throws:SocketException on error.
class
UnixAddress:
std.socket.Address;
Encapsulates an address for a Unix domain socket (AF_UNIX), i.e. a socket bound to a path name in the file system. Available only on supported systems.
Linux also supports an abstract address namespace, in which addresses are independent of the file system. A socket address is abstract iffpath starts with a null byte ('\0'). Null bytes in other positions of an abstract address are allowed and have no special meaning.
Example
auto addr =newUnixAddress("/var/run/dbus/system_bus_socket");auto abstractAddr =newUnixAddress("\0/tmp/dbus-OtHLWmCLPR");@safe this(scope const(char)[]
path);
Construct a newUnixAddress from the specified path.
pure nothrow @nogc @safe this(sockaddr_un
addr);
Construct a newUnixAddress.
Parameters:sockaddr_unaddr | A sockaddr_un as obtained from lower-level API calls. |
@property @safe string
path() const;
@safe string
toString() const;
Get the underlying path.
class
SocketAcceptException:
std.socket.SocketOSException;
Exception thrown bySocket.accept.
How a socket is shutdown:
socket receives are disallowed
socket sends are disallowed
both RECEIVE and SEND
Socket flags that may be OR'ed together:
no flags specified
out-of-band stream data
peek at incoming data without removing it from the queue, only for receiving
data should not be subject to routing; this flag may be ignored. Only for sending
Duration timeout value.
pure nothrow @nogc @property ref @safe inout(tv_sec_t)
seconds() inout return;
Number of seconds.
pure nothrow @nogc @property ref @safe inout(tv_usec_t)
microseconds() inout return;
Number of additional microseconds.
A collection of sockets for use withSocket.select.
SocketSet wraps the platformfd_set type. However, unlikefd_set,SocketSet is not statically limited toFD_SETSIZE or any other limit, and grows as needed.
pure nothrow @safe this(size_t
size = FD_SETSIZE);
Create a SocketSet with a specific initial capacity (defaults toFD_SETSIZE, the system's default capacity).
pure nothrow @nogc @safe void
reset();
Reset theSocketSet so that there are 0Sockets in the collection.
pure nothrow @safe void
add(Socket
s);
Add aSocket to the collection. The socket must not already be in the collection.
pure nothrow @safe void
remove(Socket
s);
Remove thisSocket from the collection. Does nothing if the socket is not in the collection already.
pure nothrow @nogc @safe int
isSet(Socket
s) const;
Return nonzero if thisSocket is in the collection.
pure nothrow @nogc @property @safe uint
max() const;
Returns:The current capacity of thisSocketSet. The exact meaning of the return value varies from platform to platform.
NoteSince D 2.065, this value does not indicate a restriction, andSocketSet will grow its capacity as needed automatically.
enum
SocketOptionLevel: int;
The level at which a socket option is defined:
Socket level
Internet Protocol version 4 level
Internet Control Message Protocol level
Internet Group Management Protocol level
Gateway to Gateway Protocol level
Transmission Control Protocol level
PARC Universal Packet Protocol level
User Datagram Protocol level
Xerox NS protocol level
Raw IP packet level
Internet Protocol version 6 level
Linger information for use with SocketOption.LINGER.
pure nothrow @nogc @property ref @safe inout(l_onoff_t)
on() inout return;
Nonzero for on.
pure nothrow @nogc @property ref @safe inout(l_linger_t)
time() inout return;
Linger time.
Specifies a socket option:
Record debugging information
Allow transmission of broadcast messages
Allow local reuse of address
Allow local reuse of port
Linger on close if unsent data is present
Receive out-of-band data in band
Send buffer size
Receive buffer size
Do not route
Send timeout
Receive timeout
Retrieve and clear error status
Enable keep-alive packets
Listen
Minimum number of input bytes to process
Minimum number of output bytes to process
Socket type
Disable the Nagle algorithm for send coalescing
IP unicast hop limit
IP multicast interface
IP multicast loopback
IP multicast hops
Add an IP group membership
Drop an IP group membership
Treat wildcard bind as AF_INET6-only
Class that creates a network communication endpoint using the Berkeley sockets interface.
@trusted this(AddressFamily
af, SocketType
type, ProtocolType
protocol);
@safe this(AddressFamily
af, SocketType
type);
@trusted this(AddressFamily
af, SocketType
type, scope const(char)[]
protocolName);
Create a blocking socket. If a single protocol type exists to support this socket type within the address family, theProtocolType may be omitted.
@safe this(scope const AddressInfo
info);
Create a blocking socket using the parameters from the specifiedAddressInfo structure.
pure nothrow @nogc @safe this(socket_t
sock, AddressFamily
af);
Use an existing socket handle.
pure nothrow @nogc @property @safe socket_t
handle() const;
Get underlying socket handle.
pure nothrow @nogc @property @safe socket_t
release();
Releases 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 socket - it becomes your responsibility.
To get the handle without releasing it, use thehandle property.
nothrow @nogc @property @trusted bool
blocking() const;
@property @trusted void
blocking(bool
byes);
Get/set socket's blocking flag.
When a socket is blocking, calls to receive(), accept(), and send() will block and wait for data/action. A non-blocking socket will immediately return instead of blocking.
@property @safe AddressFamily
addressFamily();
Get the socket's address family.
@property @trusted bool
isAlive() const;
Property that indicates if this is a valid, alive socket.
@trusted void
bind(Address
addr);
Associate a local address with this socket.
Parameters:Addressaddr | TheAddress to associate this socket with. |
@trusted void
connect(Address
to);
Establish 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 progress.
@trusted void
listen(int
backlog);
Listen for an incoming connection.bind must be called before you canlisten. Thebacklog is a request of how many pending incoming connections are queued untilaccepted.
protected pure nothrow @safe Socket
accepting();
Called byaccept when a newSocket must be created for a new connection. To use a derived class, override this method and return an instance of your class. The returnedSocket's handle must not be set;Socket has a protected constructorthis() to use in this situation.
Override to use a derived class. The returned socket's handle must not be set.
Accept an incoming connection. If the socket is blocking,accept waits for a connection request. ThrowsSocketAcceptException if unable to accept. Seeaccepting for use with derived classes.
nothrow @nogc @trusted void
shutdown(SocketShutdown
how);
Disables sends and/or receives.
nothrow @nogc @trusted void
close() scope;
Immediately drop any connections and release socket resources. TheSocket object is no longer usable afterclose. Callingshutdown beforeclose is recommended for connection-oriented sockets.
static @property @trusted string
hostName();
Returns:The local machine's host name
@property @trusted Address
remoteAddress();
Remote endpointAddress.
@property @trusted Address
localAddress();
Local endpointAddress.
Send or receive error code. SeewouldHaveBlocked,lastSocketError andSocket.getErrorText for obtaining more information about the error.
@trusted ptrdiff_t
send(scope const(void)[]
buf, SocketFlags
flags);
@safe ptrdiff_t
send(scope const(void)[]
buf);
Send 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, orSocket.ERROR on failure.
@trusted ptrdiff_t
sendTo(scope const(void)[]
buf, SocketFlags
flags, Address
to);
@safe ptrdiff_t
sendTo(scope const(void)[]
buf, Address
to);
@trusted ptrdiff_t
sendTo(scope const(void)[]
buf, SocketFlags
flags);
@safe ptrdiff_t
sendTo(scope const(void)[]
buf);
Send 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 space left,sendTo waits.
Returns:The number of bytes actually sent, orSocket.ERROR on failure.
@trusted ptrdiff_t
receive(scope void[]
buf, SocketFlags
flags);
@safe ptrdiff_t
receive(scope void[]
buf);
Receive 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 connection, orSocket.ERROR on failure.
@trusted ptrdiff_t
receiveFrom(scope void[]
buf, SocketFlags
flags, ref Address
from);
@safe ptrdiff_t
receiveFrom(scope void[]
buf, ref Address
from);
@trusted ptrdiff_t
receiveFrom(scope void[]
buf, SocketFlags
flags);
@safe ptrdiff_t
receiveFrom(scope void[]
buf);
Receive data and get the remote endpointAddress. If the socket is blocking,receiveFrom waits until there is data to be received.
Returns:The number of bytes actually received,0 if the remote side has closed the connection, orSocket.ERROR on failure.
@trusted int
getOption(SocketOptionLevel
level, SocketOption
option, scope void[]
result);
Get a socket option.
Returns:The number of bytes written toresult. The length, in bytes, of the actual result - very different from getsockopt()
@trusted int
getOption(SocketOptionLevel
level, SocketOption
option, out int32_t
result);
Common case of getting integer and boolean options.
@trusted int
getOption(SocketOptionLevel
level, SocketOption
option, out Linger
result);
Get the linger option.
@trusted void
getOption(SocketOptionLevel
level, SocketOption
option, out Duration
result);
Get a timeout (duration) option.
@trusted void
setOption(SocketOptionLevel
level, SocketOption
option, scope void[]
value);
Set a socket option.
@trusted void
setOption(SocketOptionLevel
level, SocketOption
option, int32_t
value);
Common case for setting integer and boolean options.
@trusted void
setOption(SocketOptionLevel
level, SocketOption
option, Linger
value);
Set the linger option.
@trusted void
setOption(SocketOptionLevel
level, SocketOption
option, Duration
value);
Sets a timeout (duration) option, i.e.SocketOption.SNDTIMEO orRCVTIMEO. Zero indicates no timeout.
In a typical application, you might also want to consider using a non-blocking socket instead of setting a timeout on a blocking one.
NoteWhile the receive timeout setting is generally quite accurate on *nix systems even for smaller durations, there are two issues to be aware of on Windows: First, although undocumented, the effective timeout duration seems to be the one set on the socket plus half a second.setOption() tries to compensate for that, but still, timeouts under 500ms are not possible on Windows. Second, be aware that the actual amount of time spent until a blocking call returns randomly varies on the order of 10ms.
Parameters:SocketOptionLevellevel | The level at which a socket option is defined. |
SocketOptionoption | EitherSocketOption.SNDTIMEO orSocketOption.RCVTIMEO. |
Durationvalue | The timeout duration to set. Must not be negative. |
Throws:SocketException if setting the options fails.
Example
import std.datetime;import std.typecons;auto pair = socketPair();scope(exit)foreach (s; pair) s.close();// Set a receive timeout, and then wait at one end of// the socket pair, knowing that no data will arrive.pair[0].setOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO, dur!"seconds"(1));auto sw = StopWatch(Yes.autoStart);ubyte[1] buffer;pair[0].receive(buffer);writefln("Waited %s ms until the socket timed out.", sw.peek.msecs);@safe string
getErrorText();
Get a text description of this socket's error status, and clear the socket's error status.
@trusted void
setKeepAlive(int
time, int
interval);
Enables TCP keep-alive with the specified parameters.
Parameters:inttime | Number of seconds with no activity until the first keep-alive packet is sent. |
intinterval | Number of seconds between when successive keep-alive packets are sent if no acknowledgement is received. |
Throws:SocketOSException if setting the options fails, orSocketFeatureException if setting keep-alive parameters is unsupported on the current platform.
static @trusted int
select(SocketSet
checkRead, SocketSet
checkWrite, SocketSet
checkError, Duration
timeout);
static @safe int
select(SocketSet
checkRead, SocketSet
checkWrite, SocketSet
checkError);
static @trusted int
select(SocketSet
checkRead, SocketSet
checkWrite, SocketSet
checkError, TimeVal*
timeout);
Wait for a socket to change status. A wait timeout of
core.time.Duration or
TimeVal, may be specified; if a timeout is not specified or the
TimeVal is
null, the maximum timeout is used. The
TimeVal timeout has an unspecified value when
select returns.
Returns:The number of sockets with status changes,
0 on timeout, or
-1 on interruption. If the return value is greater than
0, the
SocketSets are updated to only contain the sockets having status changes. For a connecting socket, a write status change means the connection is established and it's able to send. For a listening socket, a read status change means there is an incoming connection request and it's able to accept.
SocketSet's updated to include only those sockets which an event occured. For a
connect()ing socket, writeability means connected. For a
listen()ing socket, readability means listening
Winsock; possibly internally limited to 64 sockets per set.
Returns:the number of events, 0 on timeout, or -1 on interruption
protected pure nothrow @safe Address
createAddress();
Can be overridden to support other addresses.
Returns:A newAddress object for the current address family.
class
TcpSocket:
std.socket.Socket;
Shortcut class for a TCP Socket.
@safe this(AddressFamily
family);
Constructs a blocking TCP Socket.
Constructs a blocking IPv4 TCP Socket.
@safe this(Address
connectTo);
Constructs a blocking TCP Socket and connects to the givenAddress.
class
UdpSocket:
std.socket.Socket;
Shortcut class for a UDP Socket.
@safe this(AddressFamily
family);
Constructs a blocking UDP Socket.
Constructs a blocking IPv4 UDP Socket.
@trusted Socket[2]
socketPair();
Creates a pair of connected sockets.
The two sockets are indistinguishable.
Throws:SocketException if creation of the sockets fails.
Examples:immutableubyte[4] data = [1, 2, 3, 4];auto pair =socketPair();scope(exit)foreach (s; pair) s.close();pair[0].send(data[]);auto buf =newubyte[data.length];pair[1].receive(buf);writeln(buf);// data