Socket primitives.
Base exception thrown by std.socket
.
Retrieve the error message for the most recently encountered network error.
Socket exceptions representing network errors reported by the operating system.
Platform-specific error code.
Socket exceptions representing invalid parameters specified by user code.
Socket exceptions representing attempts to use network capabilities not available on the current system.
true
if the last socket operation failed because the socket was in non-blocking mode and the operation would have blocked.The communication domain used to resolve an address.
Unspecified address family
Local communication
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
Protocol
is a class for retrieving protocol information.
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");
These members are populated when one of the following functions are called successfully:
Service
is a class for retrieving service information.
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.");
These members are populated when one of the following functions are called successfully:
If a protocol name is omitted, any protocol will be matched.
Class for exceptions thrown from an InternetHost
.
InternetHost
is a class for resolving IPv4 addresses.
Consider using getAddress
, parseAddress
and Address
methods instead of using this class directly.
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); assert(ih.getHostByAddr(ih.addrList[0])); string getHostNameFromInt = ih.name.dup; assert(ih.getHostByAddr(ia.toAddrString())); string getHostNameFromStr = ih.name.dup; writeln(getHostNameFromInt); // getHostNameFromStr
These members are populated when one of the following functions are called successfully:
Resolve host name.
Resolve IPv4 address number.
uint addr
| The IPv4 address to resolve, in host byte order. |
Same as previous, but addr is an IPv4 address string in the dotted-decimal form a.b.c.d.
Holds information about a socket address retrieved by getAddressInfo
.
Address family
Socket type
Protocol
Socket address
Canonical name, when AddressInfoFlags.CANONNAME
is used.
A subset of flags supported on all platforms with getaddrinfo. Specifies option flags for getAddressInfo
.
The resulting addresses will be used in a call to Socket.bind
.
The canonical name is returned in canonicalName
member in the first AddressInfo
.
The node
parameter passed to getAddressInfo
must be a numeric string. This will suppress any potentially lengthy network host address lookups.
Provides protocol-independent translation from host names to socket addresses. If advanced functionality is not required, consider using getAddress
for compatibility with older systems.
AddressInfo
per socket address. SocketOSException
on failure, or SocketFeatureException
if this functionality is not available on the current system. const(char)[] node
| string containing host name or numeric address |
T options
| optional additional parameters, identified by type:
|
// 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);
Provides protocol-independent translation from host names to socket addresses. Uses getAddressInfo
if the current system supports it, and InternetHost
otherwise.
Address
instance per socket address. SocketOSException
on failure. 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);
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.
Address
instance representing specified address. SocketException
on failure. 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 for exceptions thrown from an Address
.
Address
is an abstract class for representing a socket addresses.
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);
Returns pointer to underlying sockaddr
structure.
Returns actual size of underlying sockaddr
structure.
Family of this address.
Attempts to retrieve the host address as a human-readable string.
AddressException
on failure, or SocketFeatureException
if address retrieval for this address family is not available on the current system.Attempts to retrieve the host name as a fully qualified domain name.
Address
, or null
if the host name did not resolve. AddressException
on error, or SocketFeatureException
if host name lookup for this address family is not available on the current system.Attempts to retrieve the numeric port number as a string.
AddressException
on failure, or SocketFeatureException
if port number retrieval for this address family is not available on the current system.Attempts to retrieve the service name as a string.
AddressException
on failure, or SocketFeatureException
if service name lookup for this address family is not available on the current system.Human readable string representing this address.
UnknownAddress
encapsulates an unknown socket address.
UnknownAddressReference
encapsulates a reference to an arbitrary socket address.
Constructs an Address
with a reference to the specified sockaddr
.
Constructs an Address
with a copy of the specified sockaddr
.
InternetAddress
encapsulates an IPv4 (Internet Protocol version 4) socket address.
Consider using getAddress
, parseAddress
and Address
methods instead of using this class directly.
Any IPv4 host address.
An invalid IPv4 host address.
Any IPv4 port number.
Returns the IPv4 port number (in host byte order).
Returns the IPv4 address number (in host byte order).
Construct a new InternetAddress
.
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 . |
Construct a new InternetAddress
.
uint addr
| (optional) an IPv4 address in host byte order, may be ADDR_ANY . |
ushort port
| port number, may be PORT_ANY . |
Construct a new InternetAddress
.
sockaddr_in addr
| A sockaddr_in as obtained from lower-level API calls such as getifaddrs. |
Human readable string representing the IPv4 address in dotted-decimal form.
Human readable string representing the IPv4 port.
Attempts to retrieve the host name as a fully qualified domain name.
InternetAddress
, or null
if the host name did not resolve. AddressException
on error.Compares with another InternetAddress of same type for equality
auto addr1 = new InternetAddress("127.0.0.1", 80); auto addr2 = new InternetAddress("127.0.0.2", 80); writeln(addr1); // addr1 assert(addr1 != addr2);
Parse an IPv4 address string in the dotted-decimal form a.b.c.d and return the number.
ADDR_NONE
is returned.Convert an IPv4 address number in host byte order to a human readable string representing the IPv4 address in dotted-decimal form.
Internet6Address
encapsulates an IPv6 (Internet Protocol version 6) socket address.
Consider using getAddress
, parseAddress
and Address
methods instead of using this class directly.
Any IPv6 host address.
Any IPv6 port number.
Returns the IPv6 port number.
Returns the IPv6 address.
Construct a new Internet6Address
.
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. |
Construct a new Internet6Address
.
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 . |
Construct a new Internet6Address
.
ubyte[16] addr
| (optional) an IPv6 host address in host byte order, or ADDR_ANY . |
ushort port
| port number, may be PORT_ANY . |
Construct a new Internet6Address
.
sockaddr_in6 addr
| A sockaddr_in6 as obtained from lower-level API calls such as getifaddrs. |
Parse an IPv6 host address string as described in RFC 2373, and return the address.
SocketException
on error.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.
auto addr = new UnixAddress("/var/run/dbus/system_bus_socket"); auto abstractAddr = new UnixAddress("\0/tmp/dbus-OtHLWmCLPR");
Construct a new UnixAddress
from the specified path.
Construct a new UnixAddress
.
sockaddr_un addr
| A sockaddr_un as obtained from lower-level API calls. |
Get the underlying path.
Class for exceptions thrown by Socket.accept
.
How a socket is shutdown:
socket receives are disallowed
socket sends are disallowed
both RECEIVE and SEND
Flags 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.
Number of seconds.
Number 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.
Create a SocketSet with a specific initial capacity (defaults to FD_SETSIZE
, the system's default capacity).
Reset the SocketSet
so that there are 0 Socket
s in the collection.
Add a Socket
to the collection. The socket must not already be in the collection.
Remove this Socket
from the collection. Does nothing if the socket is not in the collection already.
Return nonzero if this Socket
is in the collection.
SocketSet
. The exact meaning of the return value varies from platform to platform. SocketSet
will grow its capacity as needed automatically.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.
Nonzero for on.
Linger time.
Specifies a socket option:
Record debugging information
Allow transmission of broadcast messages
Allow local reuse of address
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
Socket
is a class that creates a network communication endpoint using the Berkeley sockets interface.
Create a blocking socket. If a single protocol type exists to support this socket type within the address family, the ProtocolType
may be omitted.
Create a blocking socket using the parameters from the specified AddressInfo
structure.
Use an existing socket handle.
Get underlying socket handle.
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.
Get the socket's address family.
Property that indicates if this is a valid, alive socket.
Associate a local address with this socket.
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.
Listen 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.
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.
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.
Disables sends and/or receives.
Immediately 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.
Remote endpoint Address
.
Local endpoint Address
.
Send or receive error code. See wouldHaveBlocked
, lastSocketError
and Socket.getErrorText
for obtaining more information about the error.
Send data on the connection. If the socket is blocking and there is no buffer space left, send
waits.
Socket.ERROR
on failure.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.
Socket.ERROR
on failure.Receive data on the connection. If the socket is blocking, receive
waits until there is data to be received.
0
if the remote side has closed the connection, or Socket.ERROR
on failure.Receive data and get the remote endpoint Address
. If the socket is blocking, receiveFrom
waits until there is data to be received.
0
if the remote side has closed the connection, or Socket.ERROR
on failure.Get a socket option.
result
. The length, in bytes, of the actual result - very different from getsockopt()Common case of getting integer and boolean options.
Get the linger option.
Get a timeout (duration) option.
Set a socket option.
Common case for setting integer and boolean options.
Set the linger option.
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.
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. 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. |
SocketException
if setting the options fails. 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);
Get a text description of this socket's error status, and clear the socket's error status.
Enables TCP keep-alive with the specified 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. |
SocketOSException
if setting the options fails, or SocketFeatureException
if setting keep-alive parameters is unsupported on the current platform.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.
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. Can be overridden to support other addresses.
Address
object for the current address family.TcpSocket
is a shortcut class for a TCP Socket.
Constructs a blocking TCP Socket.
Constructs a blocking IPv4 TCP Socket.
Constructs a blocking TCP Socket and connects to an Address
.
UdpSocket
is a shortcut class for a UDP Socket.
Constructs a blocking UDP Socket.
Constructs a blocking IPv4 UDP Socket.
Creates a pair of connected sockets.
The two sockets are indistinguishable.
SocketException
if creation of the sockets fails.immutable ubyte[] 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
© 1999–2019 The D Language Foundation
Licensed under the Boost License 1.0.
https://dlang.org/phobos/std_socket.html