Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

std.socket

Example:
See /dmd/samples/d/listener.d and /dmd/samples/d/htmlget.d

License:
Boost License 1.0.

Authors:
Christopher E. Miller, David Nadlinger, Vladimir Panteleev

Source:
std/socket.d

class SocketException: object.Exception;
Base exception thrown by std.socket.

this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null);

this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__);

@property 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.

this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null, int err = _lasterr(), string function(int) errorFormatter = &formatSocketError);

this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__, int err = _lasterr(), string function(int) errorFormatter = &formatSocketError);

this(string msg, int err, string function(int) errorFormatter = &formatSocketError, string file = __FILE__, size_t line = __LINE__, Throwable next = null);

class SocketParameterException: std.socket.SocketException;
Socket exceptions representing invalid parameters specified by user code.

this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null);

this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__);

class SocketFeatureException: std.socket.SocketException;
Socket exceptions representing attempts to use network capabilities not available on the current system.

this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null);

this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__);

bool wouldHaveBlocked();
Return true if the last socket operation failed because the socket was in non-blocking mode and the operation would have blocked.

enum AddressFamily: int;
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;
string name;
string[] aliases;
These members are populated when one of the following functions are called successfully:

bool getProtocolByName(in char[] name);
Returns:
false on failure

bool getProtocolByType(ProtocolType type);
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;
ushort port;
string protocolName;
These members are populated when one of the following functions are called successfully:

bool getServiceByName(in char[] name, in char[] protocolName = null);
bool getServiceByPort(ushort port, in 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.

this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null, int err = _lasterr());

this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__, int err = _lasterr());

this(string msg, int err, string file = __FILE__, size_t line = __LINE__, Throwable next = null);

class InternetHost;
InternetHost is a class for resolving IPv4 addresses.

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

Example:
auto ih = new InternetHost;

// Forward lookup
writeln("About www.digitalmars.com:");
if (ih.getHostByName("www.digitalmars.com"))
{
    writefln("  Name: %s", ih.name);
    auto ip = InternetAddress.addrToString(ih.addrList[0]);
    writefln("  IP address: %s", ip);
    foreach (string s; ih.aliases)
         writefln("  Alias: %s", s);
    writeln("---");

    // Reverse lookup
    writefln("About IP %s:", ip);
    if (ih.getHostByAddr(ih.addrList[0]))
    {
        writefln("  Name: %s", ih.name);
        foreach (string s; ih.aliases)
             writefln("  Alias: %s", s);
    }
    else
        writeln("  Reverse lookup failed");
}
else
    writeln("  Can't resolve www.digitalmars.com");

string name;
string[] aliases;
uint[] addrList;
These members are populated when one of the following functions are called successfully:

bool getHostByName(in char[] name);
Resolve host name.

Returns:
false if unable to resolve.

bool getHostByAddr(uint addr);
Resolve IPv4 address number.

Parameters:
uint addr The IPv4 address to resolve, in host byte order.

Returns:
false if unable to resolve.

bool getHostByAddr(in 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;
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...)(in char[] node, 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.

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:
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);

Address[] getAddress(in char[] hostname, in char[] service = null);
Address[] getAddress(in char[] hostname, ushort port);
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);

Address parseAddress(in char[] hostaddr, in char[] service = null);
Address parseAddress(in char[] hostaddr, ushort port);
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.

this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null, int err = _lasterr());

this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__, int err = _lasterr());

this(string msg, int err, string file = __FILE__, size_t line = __LINE__, Throwable next = null);

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 @property sockaddr* name();
abstract const @property const(sockaddr)* name();
Returns pointer to underlying sockaddr structure.

abstract const @property socklen_t nameLen();
Returns actual size of underlying sockaddr structure.

const @property AddressFamily addressFamily();
Family of this address.

const 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 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 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 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 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.

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.

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.

uint ADDR_ANY;
Any IPv4 host address.

uint ADDR_NONE;
An invalid IPv4 host address.

ushort PORT_ANY;
Any IPv4 port number.

const @property ushort port();
Returns the IPv4 port number (in host byte order).

const @property uint addr();
Returns the IPv4 address number (in host byte order).

this(in char[] addr, ushort port);
Construct a new InternetAddress.

Parameters:
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.

this(uint addr, ushort port);
this(ushort port);
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.

const string toAddrString();
Human readable string representing the IPv4 address in dotted-decimal form.

const string toPortString();
Human readable string representing the IPv4 port.

const 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.

static uint parse(in 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 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;
Internet6Address encapsulates an IPv6 (Internet Protocol version 6) socket address.

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

static @property ref const(ubyte)[16] ADDR_ANY();
Any IPv6 host address.

ushort PORT_ANY;
Any IPv6 port number.

const @property ushort port();
Returns the IPv6 port number.

const @property ubyte[16] addr();
Returns the IPv6 address.

this(in char[] addr, in char[] service = null);
Construct a new Internet6Address.

Parameters:
char[] addr an IPv6 host address string in the form described in RFC 2373, or a host name which will be resolved using getAddressInfo.
char[] service (optional) service name.

this(in char[] addr, ushort port);
Construct a new Internet6Address.

Parameters:
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.

this(ubyte[16] addr, ushort port);
this(ushort port);
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.

static ubyte[16] parse(in char[] addr);
Parse an IPv6 host address string as described in RFC 2373, and return the address.

Throws:
SocketException on error.

abstract class UnixAddress: std.socket.Address;
UnixAddress encapsulates an address for a Unix domain socket (AF_UNIX). Available only on supported systems.

this(in char[] path);
Construct a new UnixAddress from the specified path.

const @property string path();
const string toString();
Get the underlying path.

class SocketAcceptException: std.socket.SocketOSException;
Class for exceptions thrown by Socket.accept.

this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null, int err = _lasterr());

this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__, int err = _lasterr());

this(string msg, int err, string file = __FILE__, size_t line = __LINE__, Throwable next = null);

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.

tv_sec_t seconds;
Number of seconds.

tv_usec_t microseconds;
Number of additional microseconds.

class SocketSet;
A collection of sockets for use with Socket.select.

SocketSet allows specifying the capacity of the underlying fd_set, however users should be aware that the exact meaning of this value varies depending on the current platform:
  • On POSIX, fd_set is a bit array of file descriptors. The SocketSet capacity specifies the highest file descriptor which can be stored in the set.
  • on Windows, fd_set is an array of socket handles. Capacity indicates the actual number of sockets that can be stored in the set.

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.

l_onoff_t on;
Nonzero for on.

l_linger_t time;
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.

class TcpSocket: std.socket.Socket;
TcpSocket is a shortcut class for a TCP Socket.

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 an Address.

class UdpSocket: std.socket.Socket;
UdpSocket is a shortcut class for a UDP Socket.

this(AddressFamily family);
Constructs a blocking UDP Socket.

this();
Constructs a blocking IPv4 UDP Socket.

Socket[2] socketPair();
Creates a pair of connected sockets.

The two sockets are indistinguishable.

Throws:
SocketException if creation of the sockets fails.

Example:
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);
assert(buf == data);