std.socket
Example See /dmd/compiler/samples/listener.d and /dmd/compiler/samples/htmlget.d
Source std/socket.d
- class
SocketException
: object.Exception; - Base exception thrown by std.socket.
- @property @safe string
lastSocketError
(); - Retrieve the error message for the most recently encountered network error.
- class
SocketOSException
: std.socket.SocketException; - Socket exceptions representing network errors reported by the operating system.
- int
errorCode
; - Platform-specific error code.
- @safe this(string
msg
, stringfile
= __FILE__, size_tline
= __LINE__, Throwablenext
= null, interr
= _lasterr(), string function(int) @trustederrorFormatter
= &formatSocketError); - @safe this(string
msg
, Throwablenext
, stringfile
= __FILE__, size_tline
= __LINE__, interr
= _lasterr(), string function(int) @trustederrorFormatter
= &formatSocketError); - @safe this(string
msg
, interr
, string function(int) @trustederrorFormatter
= &formatSocketError, stringfile
= __FILE__, size_tline
= __LINE__, Throwablenext
= null);
- class
SocketParameterException
: std.socket.SocketException; - Socket exceptions representing invalid parameters specified by user code.
- class
SocketFeatureException
: std.socket.SocketException; - Socket exceptions 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 a SNDTIMEO or RCVTIMEO, and the operation timed out.
- enum
AddressFamily
: ushort; - The communication domain used to resolve an address.
UNSPEC
- Unspecified address family
UNIX
- Local communication
INET
- Internet Protocol version 4
IPX
- Novell IPX
APPLETALK
- AppleTalk
INET6
- Internet Protocol version 6
- enum
SocketType
: int; - Communication semantics
STREAM
- Sequenced, reliable, two-way communication-based byte streams
DGRAM
- Connectionless, unreliable datagrams with a fixed maximum length; data may be lost or arrive out of order
RAW
- Raw protocol access
RDM
- Reliably-delivered message datagrams
SEQPACKET
- Sequenced, reliable, two-way connection-based datagrams with a fixed maximum length
- enum
ProtocolType
: int; - Protocol
IP
- Internet Protocol version 4
ICMP
- Internet Control Message Protocol
IGMP
- Internet Group Management Protocol
GGP
- Gateway to Gateway Protocol
TCP
- Transmission Control Protocol
PUP
- PARC Universal Packet Protocol
UDP
- User Datagram Protocol
IDP
- Xerox NS protocol
RAW
- Raw IP packets
IPV6
- Internet Protocol version 6
- class
Protocol
; Protocol
is a 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");
- ProtocolType
type
;
stringname
;
string[]aliases
; - These members are populated when one of the following functions are called successfully:
- nothrow @trusted bool
getProtocolByName
(scope const(char)[]name
); - Returns:false on failure
- nothrow @trusted bool
getProtocolByType
(ProtocolTypetype
); - Returns:false on failure
- class
Service
; Service
is a 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.");
- string
name
;
string[]aliases
;
ushortport
;
stringprotocolName
; - 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 boolgetServiceByPort
(ushortport
, 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 an InternetHost.
- class
InternetHost
; InternetHost
is a class for resolving IPv4 addresses.Consider using getAddress, parseAddress and Address methods instead of using this class directly.Examples:InternetHost ih = new InternetHost; ih.getHostByAddr(0x7F_00_00_01); writeln(ih.addrList[0]); // 0x7F_00_00_01 ih.getHostByAddr("127.0.0.1"); writeln(ih.addrList[0]); // 0x7F_00_00_01 if (!ih.getHostByName("www.digitalmars.com")) return; // don't fail if not connected to internet assert(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
(uintaddr
); - Resolve IPv4 address number.Parameters:
uint addr
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 form a.b.c.d.Returns:false if unable to resolve.
- struct
AddressInfo
; - Holds information about a socket address retrieved by getAddressInfo.
- AddressFamily
family
; - Address family
- SocketType
type
; - Socket type
- ProtocolType
protocol
; - Protocol
- Address
address
; - Socket address
- string
canonicalName
; - Canonical name, when AddressInfoFlags.CANONNAME is used.
- enum
AddressInfoFlags
: int; - A subset of flags supported on all platforms with getaddrinfo. Specifies option flags for getAddressInfo.
PASSIVE
- The resulting addresses will be used in a call to Socket.bind.
CANONNAME
- The canonical name is returned in canonicalName member in the first AddressInfo.
NUMERICHOST
- The node parameter passed to getAddressInfo must be a numeric string. This will suppress any potentially lengthy network host address lookups.
- AddressInfo[]
getAddressInfo
(T...)(scope const(char)[]node
, scope Toptions
); - Provides protocol-independent translation from host names to socket addresses. If advanced functionality is not required, consider using getAddress for compatibility with older systems.Returns:Array with one AddressInfo per socket address.Throws:SocketOSException on failure, or SocketFeatureException if this functionality is not available on the current system.Parameters:
const(char)[] node
string containing host name or numeric address T options
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 resolution auto results = getAddressInfo("www.digitalmars.com"); assert(results[0].address.toHostNameString() == "digitalmars.com"); // Canonical name results = getAddressInfo("www.digitalmars.com", AddressInfoFlags.CANONNAME); assert(results[0].canonicalName == "digitalmars.com"); // IPv6 resolution results = getAddressInfo("ipv6.google.com"); assert(results[0].family == AddressFamily.INET6); // Multihomed resolution results = getAddressInfo("google.com"); assert(results.length > 1); // Parsing IPv4 results = getAddressInfo("127.0.0.1", AddressInfoFlags.NUMERICHOST); assert(results.length && results[0].family == AddressFamily.INET); // Parsing IPv6 results = 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
, ushortport
); - Provides protocol-independent translation from host names to socket addresses. Uses getAddressInfo if the current system supports it, and InternetHost otherwise.Returns:Array with one Address 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 AddressparseAddress
(scope const(char)[]hostaddr
, ushortport
); - Provides protocol-independent parsing of network addresses. Does not attempt name resolution. Uses getAddressInfo with AddressInfoFlags.NUMERICHOST if the current system supports it, and InternetAddress otherwise.Returns:An Address 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 an Address.
- abstract class
Address
; Address
is an abstract class for representing a socket addresses.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 const pure nothrow @nogc @property @safe const(sockaddr)*name
(); - Returns pointer to underlying sockaddr structure.
- abstract const pure nothrow @nogc @property @safe socklen_t
nameLen
(); - Returns actual size of underlying sockaddr structure.
- const pure nothrow @nogc @property @safe AddressFamily
addressFamily
(); - Family of this address.
- const @safe string
toAddrString
(); - Attempts to retrieve the host address as a human-readable string.Throws:AddressException on failure, or SocketFeatureException if address retrieval for this address family is not available on the current system.
- const @safe string
toHostNameString
(); - Attempts to retrieve the host name as a fully qualified domain name.Returns:The FQDN corresponding to this Address, or null if the host name did not resolve.Throws:AddressException on error, or SocketFeatureException if host name lookup for this address family is not available on the current system.
- const @safe string
toPortString
(); - Attempts to retrieve the numeric port number as a string.Throws:AddressException on failure, or SocketFeatureException if port number retrieval for this address family is not available on the current system.
- const @safe string
toServiceNameString
(); - Attempts to retrieve the service name as a string.Throws:AddressException on failure, or SocketFeatureException if service name lookup for this address family is not available on the current system.
- const @safe string
toString
(); - Human readable string representing this address.
- class
UnknownAddress
: std.socket.Address; UnknownAddress
encapsulates an unknown socket address.- class
UnknownAddressReference
: std.socket.Address; UnknownAddressReference
encapsulates a reference to an arbitrary socket address.- pure nothrow @nogc @safe this(sockaddr*
sa
, socklen_tlen
); - Constructs an Address with a reference to the specified sockaddr.
- pure nothrow @system this(const(sockaddr)*
sa
, socklen_tlen
); - Constructs an Address with a copy of the specified sockaddr.
- class
InternetAddress
: std.socket.Address; InternetAddress
encapsulates an IPv4 (Internet Protocol version 4) socket address.Consider using getAddress, parseAddress and Address methods instead of using this class directly.- enum uint
ADDR_ANY
; - Any IPv4 host address.
- enum uint
ADDR_NONE
; - An invalid IPv4 host address.
- enum ushort
PORT_ANY
; - Any IPv4 port number.
- const pure nothrow @nogc @property @safe ushort
port
(); - Returns the IPv4 port number (in host byte order).
- const pure nothrow @nogc @property @safe uint
addr
(); - Returns the IPv4 address number (in host byte order).
- @safe this(scope const(char)[]
addr
, ushortport
); - Construct a new InternetAddress.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 an InternetHost object. ushort port
port number, may be PORT_ANY. - pure nothrow @nogc @safe this(uint
addr
, ushortport
);
pure nothrow @nogc @safe this(ushortport
); - Construct a new InternetAddress.Parameters:
uint addr
(optional) an IPv4 address in host byte order, may be ADDR_ANY. ushort port
port number, may be PORT_ANY. - pure nothrow @nogc @safe this(sockaddr_in
addr
); - Construct a new InternetAddress.Parameters:
sockaddr_in addr
A sockaddr_in as obtained from lower-level API calls such as getifaddrs. - const @trusted string
toAddrString
(); - Human readable string representing the IPv4 address in dotted-decimal form.
- const @safe string
toPortString
(); - Human readable string representing the IPv4 port.
- const @safe string
toHostNameString
(); - Attempts to retrieve the host name as a fully qualified domain name.Returns:The FQDN corresponding to this InternetAddress, or null if the host name did not resolve.Throws:AddressException on error.
- const @safe bool
opEquals
(Objecto
); - Compares with another InternetAddress of same type for equalityReturns: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); // addr1 assert(addr1 != addr2);
- static nothrow @trusted uint
parse
(scope const(char)[]addr
); - Parse 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.
- static nothrow @trusted string
addrToString
(uintaddr
); - 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; Internet6Address
encapsulates an IPv6 (Internet Protocol version 6) socket address.Consider using getAddress, parseAddress and Address methods instead of using this class directly.- static pure nothrow @nogc @property ref @safe const(ubyte)[16]
ADDR_ANY
(); - Any IPv6 host address.
- enum ushort
PORT_ANY
; - Any IPv6 port number.
- const pure nothrow @nogc @property @safe ushort
port
(); - Returns the IPv6 port number.
- const pure nothrow @nogc @property @safe ubyte[16]
addr
(); - Returns the IPv6 address.
- @trusted this(scope const(char)[]
addr
, scope const(char)[]service
= null); - Construct a new Internet6Address.Parameters:
const(char)[] addr
an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved using getAddressInfo. const(char)[] service
(optional) service name. - @safe this(scope const(char)[]
addr
, ushortport
); - Construct a new Internet6Address.Parameters:
const(char)[] addr
an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved using getAddressInfo. ushort port
port number, may be PORT_ANY. - pure nothrow @nogc @safe this(ubyte[16]
addr
, ushortport
);
pure nothrow @nogc @safe this(ushortport
); - Construct a new Internet6Address.Parameters:
ubyte[16] addr
(optional) an IPv6 host address in host byte order, or ADDR_ANY. ushort port
port number, may be PORT_ANY. - pure nothrow @nogc @safe this(sockaddr_in6
addr
); - Construct a new Internet6Address.Parameters:
sockaddr_in6 addr
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; UnixAddress
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 iff path 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 = new UnixAddress("/var/run/dbus/system_bus_socket"); auto abstractAddr = new UnixAddress("\0/tmp/dbus-OtHLWmCLPR");
See Also:- @safe this(scope const(char)[]
path
); - Construct a new UnixAddress from the specified path.
- pure nothrow @nogc @safe this(sockaddr_un
addr
); - Construct a new UnixAddress.Parameters:
sockaddr_un addr
A sockaddr_un as obtained from lower-level API calls. - const @property @safe string
path
();
const @safe stringtoString
(); - Get the underlying path.
- class
SocketAcceptException
: std.socket.SocketOSException; - Class for exceptions thrown by Socket.accept.
- enum
SocketShutdown
: int; - How a socket is shutdown:
RECEIVE
- socket receives are disallowed
SEND
- socket sends are disallowed
BOTH
- both RECEIVE and SEND
- enum
SocketFlags
: int; - Flags may be OR'ed together:
NONE
- no flags specified
OOB
- out-of-band stream data
PEEK
- peek at incoming data without removing it from the queue, only for receiving
DONTROUTE
- data should not be subject to routing; this flag may be ignored. Only for sending
- struct
TimeVal
; - Duration timeout value.
- inout pure nothrow @nogc @property ref @safe inout(tv_sec_t)
seconds
() return; - Number of seconds.
- inout pure nothrow @nogc @property ref @safe inout(tv_usec_t)
microseconds
() return; - Number of additional microseconds.
- class
SocketSet
; - 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.- pure nothrow @safe this(size_t
size
= FD_SETSIZE); - Create a SocketSet with a specific initial capacity (defaults to FD_SETSIZE, the system's default capacity).
- pure nothrow @nogc @safe void
reset
(); - Reset the SocketSet so that there are 0 Sockets in the collection.
- pure nothrow @safe void
add
(Sockets
); - Add a Socket to the collection. The socket must not already be in the collection.
- pure nothrow @safe void
remove
(Sockets
); - Remove this Socket from the collection. Does nothing if the socket is not in the collection already.
- const pure nothrow @nogc @safe int
isSet
(Sockets
); - Return nonzero if this Socket is in the collection.
- const pure nothrow @nogc @property @safe uint
max
(); - Returns:The current capacity of this SocketSet. The exact meaning of the return value varies from platform to platform.
Note Since D 2.065, this value does not indicate a restriction, and SocketSet will grow its capacity as needed automatically.
- enum
SocketOptionLevel
: int; - The level at which a socket option is defined:
SOCKET
- Socket level
IP
- Internet Protocol version 4 level
ICMP
- Internet Control Message Protocol level
IGMP
- Internet Group Management Protocol level
GGP
- Gateway to Gateway Protocol level
TCP
- Transmission Control Protocol level
PUP
- PARC Universal Packet Protocol level
UDP
- User Datagram Protocol level
IDP
- Xerox NS protocol level
RAW
- Raw IP packet level
IPV6
- Internet Protocol version 6 level
- struct
Linger
; - Linger information for use with SocketOption.LINGER.
- inout pure nothrow @nogc @property ref @safe inout(l_onoff_t)
on
() return; - Nonzero for on.
- inout pure nothrow @nogc @property ref @safe inout(l_linger_t)
time
() return; - Linger time.
- enum
SocketOption
: int; - Specifies a socket option:
DEBUG
- Record debugging information
BROADCAST
- Allow transmission of broadcast messages
REUSEADDR
- Allow local reuse of address
LINGER
- Linger on close if unsent data is present
OOBINLINE
- Receive out-of-band data in band
SNDBUF
- Send buffer size
RCVBUF
- Receive buffer size
DONTROUTE
- Do not route
SNDTIMEO
- Send timeout
RCVTIMEO
- Receive timeout
ERROR
- Retrieve and clear error status
KEEPALIVE
- Enable keep-alive packets
ACCEPTCONN
- Listen
RCVLOWAT
- Minimum number of input bytes to process
SNDLOWAT
- Minimum number of output bytes to process
TYPE
- Socket type
TCP_NODELAY
- Disable the Nagle algorithm for send coalescing
IPV6_UNICAST_HOPS
- IP unicast hop limit
IPV6_MULTICAST_IF
- IP multicast interface
IPV6_MULTICAST_LOOP
- IP multicast loopback
IPV6_MULTICAST_HOPS
- IP multicast hops
IPV6_JOIN_GROUP
- Add an IP group membership
IPV6_LEAVE_GROUP
- Drop an IP group membership
IPV6_V6ONLY
- Treat wildcard bind as AF_INET6-only
- class
Socket
; Socket
is a class that creates a network communication endpoint using the Berkeley sockets interface.- @trusted this(AddressFamily
af
, SocketTypetype
, ProtocolTypeprotocol
);
@safe this(AddressFamilyaf
, SocketTypetype
);
@trusted this(AddressFamilyaf
, SocketTypetype
, scope const(char)[]protocolName
); - Create a blocking socket. If a single protocol type exists to support this socket type within the address family, the ProtocolType may be omitted.
- @safe this(scope const AddressInfo
info
); - Create a blocking socket using the parameters from the specified AddressInfo structure.
- pure nothrow @nogc @safe this(socket_t
sock
, AddressFamilyaf
); - Use an existing socket handle.
- const pure nothrow @nogc @property @safe socket_t
handle
(); - 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 the handle property.
- const nothrow @nogc @property @trusted bool
blocking
();
@property @trusted voidblocking
(boolbyes
); - 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.
- const @property @trusted bool
isAlive
(); - Property that indicates if this is a valid, alive socket.
- @trusted void
bind
(Addressaddr
); - Associate a local address with this socket.Parameters:
Address addr
The Address to associate this socket with. Throws:SocketOSException when unable to bind the socket. - @trusted void
connect
(Addressto
); - 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
(intbacklog
); - Listen for an incoming connection. bind must be called before you can
listen
. Thebacklog
is a request of how many pending incoming connections are queued until accepted. - protected pure nothrow @safe Socket
accepting
(); - Called 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 not be set; Socket has a protected constructor this() to use in this situation.Override to use a derived class. The returned socket's handle must not be set.
- @trusted Socket
accept
(); - Accept 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. - nothrow @nogc @trusted void
shutdown
(SocketShutdownhow
); - Disables sends and/or receives.
- nothrow @nogc scope @trusted void
close
(); - Immediately drop any connections and release socket resources. The Socket object is no longer usable after
close
. Calling shutdown beforeclose
is recommended for connection-oriented sockets. - static @property @trusted string
hostName
(); - Returns:the local machine's host name
- @property @trusted Address
remoteAddress
(); - Remote endpoint Address.
- @property @trusted Address
localAddress
(); - Local endpoint Address.
- enum int
ERROR
; - Send or receive error code. See wouldHaveBlocked, lastSocketError and Socket.getErrorText for obtaining more information about the error.
- @trusted ptrdiff_t
send
(scope const(void)[]buf
, SocketFlagsflags
);
@safe ptrdiff_tsend
(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, or Socket.ERROR on failure. - @trusted ptrdiff_t
sendTo
(scope const(void)[]buf
, SocketFlagsflags
, Addressto
);
@safe ptrdiff_tsendTo
(scope const(void)[]buf
, Addressto
);
@trusted ptrdiff_tsendTo
(scope const(void)[]buf
, SocketFlagsflags
);
@safe ptrdiff_tsendTo
(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, or Socket.ERROR on failure. - @trusted ptrdiff_t
receive
(scope void[]buf
, SocketFlagsflags
);
@safe ptrdiff_treceive
(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, or Socket.ERROR on failure. - @trusted ptrdiff_t
receiveFrom
(scope void[]buf
, SocketFlagsflags
, ref Addressfrom
);
@safe ptrdiff_treceiveFrom
(scope void[]buf
, ref Addressfrom
);
@trusted ptrdiff_treceiveFrom
(scope void[]buf
, SocketFlagsflags
);
@safe ptrdiff_treceiveFrom
(scope void[]buf
); - Receive 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 remote side has closed the connection, or Socket.ERROR on failure. - @trusted int
getOption
(SocketOptionLevellevel
, SocketOptionoption
, scope void[]result
); - Get a socket option.Returns:The number of bytes written to
result
. The length, in bytes, of the actual result - very different from getsockopt() - @trusted int
getOption
(SocketOptionLevellevel
, SocketOptionoption
, out int32_tresult
); - Common case of getting integer and boolean options.
- @trusted int
getOption
(SocketOptionLevellevel
, SocketOptionoption
, out Lingerresult
); - Get the linger option.
- @trusted void
getOption
(SocketOptionLevellevel
, SocketOptionoption
, out Durationresult
); - Get a timeout (duration) option.
- @trusted void
setOption
(SocketOptionLevellevel
, SocketOptionoption
, scope void[]value
); - Set a socket option.
- @trusted void
setOption
(SocketOptionLevellevel
, SocketOptionoption
, int32_tvalue
); - Common case for setting integer and boolean options.
- @trusted void
setOption
(SocketOptionLevellevel
, SocketOptionoption
, Lingervalue
); - Set the linger option.
- @trusted void
setOption
(SocketOptionLevellevel
, SocketOptionoption
, Durationvalue
); - Sets a timeout (duration) option, i.e. SocketOption.SNDTIMEO or RCVTIMEO. 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.
Note While 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:SocketOptionLevel level
The level at which a socket option is defined. SocketOption option
Either SocketOption.SNDTIMEO or SocketOption.RCVTIMEO. Duration value
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
(inttime
, intinterval
); - Enables TCP keep-alive with the specified parameters.Parameters:
int time
Number of seconds with no activity until the first keep-alive packet is sent. int interval
Number of seconds between when successive keep-alive packets are sent if no acknowledgement is received. Throws:SocketOSException if setting the options fails, or SocketFeatureException if setting keep-alive parameters is unsupported on the current platform. - static @trusted int
select
(SocketSetcheckRead
, SocketSetcheckWrite
, SocketSetcheckError
, Durationtimeout
);
static @safe intselect
(SocketSetcheckRead
, SocketSetcheckWrite
, SocketSetcheckError
);
static @trusted intselect
(SocketSetcheckRead
, SocketSetcheckWrite
, SocketSetcheckError
, 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 new Address object for the current address family.
- class
TcpSocket
: std.socket.Socket; TcpSocket
is a shortcut class for a TCP Socket.- @safe this(AddressFamily
family
); - Constructs a blocking TCP Socket.
- @safe this();
- Constructs a blocking IPv4 TCP Socket.
- @safe this(Address
connectTo
); - Constructs a blocking TCP Socket and connects to an Address.
- class
UdpSocket
: std.socket.Socket; UdpSocket
is a shortcut class for a UDP Socket.- @safe this(AddressFamily
family
); - Constructs a blocking UDP Socket.
- @safe this();
- 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:
immutable ubyte[4] data = [1, 2, 3, 4]; auto pair = socketPair(); scope(exit) foreach (s; pair) s.close(); pair[0].send(data[]); auto buf = new ubyte[data.length]; pair[1].receive(buf); writeln(buf); // data