/std/socket.d
http://github.com/jcd/phobos · D · 3276 lines · 2021 code · 414 blank · 841 comment · 255 complexity · 02a5746ae79a3ff545995366b2eb4268 MD5 · raw file
Large files are truncated click here to view the full file
- // Written in the D programming language
- /*
- Copyright (C) 2004-2011 Christopher E. Miller
- Boost Software License - Version 1.0 - August 17th, 2003
- Permission is hereby granted, free of charge, to any person or organization
- obtaining a copy of the software and accompanying documentation covered by
- this license (the "Software") to use, reproduce, display, distribute,
- execute, and transmit the Software, and to prepare derivative works of the
- Software, and to permit third-parties to whom the Software is furnished to
- do so, all subject to the following:
- The copyright notices in the Software and this entire statement, including
- the above license grant, this restriction and the following disclaimer,
- must be included in all copies of the Software, in whole or in part, and
- all derivative works of the Software, unless such copies or derivative
- works are solely in the form of machine-executable object code generated by
- a source language processor.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
- SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
- FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- DEALINGS IN THE SOFTWARE.
- socket.d 1.4
- Jan 2011
- Thanks to Benjamin Herr for his assistance.
- */
- /**
- * Example: See $(SAMPLESRC listener.d) and $(SAMPLESRC htmlget.d)
- * License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
- * Authors: Christopher E. Miller, $(WEB klickverbot.at, David Nadlinger),
- * $(WEB thecybershadow.net, Vladimir Panteleev)
- * Source: $(PHOBOSSRC std/_socket.d)
- * Macros:
- * WIKI=Phobos/StdSocket
- */
- module std.socket;
- import core.stdc.stdint, std.string, std.c.string, std.c.stdlib, std.conv;
- import core.stdc.config;
- import core.time : dur, Duration;
- import std.algorithm : max;
- import std.exception : assumeUnique, enforce, collectException;
- version(Windows)
- {
- pragma (lib, "ws2_32.lib");
- pragma (lib, "wsock32.lib");
- private import std.c.windows.windows, std.c.windows.winsock, std.windows.syserror;
- private alias std.c.windows.winsock.timeval _ctimeval;
- private alias std.c.windows.winsock.linger _clinger;
- enum socket_t : SOCKET { INVALID_SOCKET }
- private const int _SOCKET_ERROR = SOCKET_ERROR;
- private int _lasterr()
- {
- return WSAGetLastError();
- }
- }
- else version(Posix)
- {
- version(linux)
- import std.c.linux.socket : AF_IPX, AF_APPLETALK, SOCK_RDM,
- IPPROTO_IGMP, IPPROTO_GGP, IPPROTO_PUP, IPPROTO_IDP,
- SD_RECEIVE, SD_SEND, SD_BOTH, MSG_NOSIGNAL, INADDR_NONE,
- TCP_KEEPIDLE, TCP_KEEPINTVL;
- else version(OSX)
- import std.c.osx.socket : AF_IPX, AF_APPLETALK, SOCK_RDM,
- IPPROTO_IGMP, IPPROTO_GGP, IPPROTO_PUP, IPPROTO_IDP,
- SD_RECEIVE, SD_SEND, SD_BOTH, INADDR_NONE;
- else version(FreeBSD)
- {
- import core.sys.posix.sys.socket;
- import core.sys.posix.sys.select;
- import std.c.freebsd.socket;
- private enum SD_RECEIVE = SHUT_RD;
- private enum SD_SEND = SHUT_WR;
- private enum SD_BOTH = SHUT_RDWR;
- }
- else
- static assert(false);
- import core.sys.posix.netdb;
- import core.sys.posix.sys.un : sockaddr_un;
- private import core.sys.posix.fcntl;
- private import core.sys.posix.unistd;
- private import core.sys.posix.arpa.inet;
- private import core.sys.posix.netinet.tcp;
- private import core.sys.posix.netinet.in_;
- private import core.sys.posix.sys.time;
- //private import core.sys.posix.sys.select;
- private import core.sys.posix.sys.socket;
- private alias core.sys.posix.sys.time.timeval _ctimeval;
- private alias core.sys.posix.sys.socket.linger _clinger;
- private import core.stdc.errno;
- enum socket_t : int32_t { init = -1 }
- private const int _SOCKET_ERROR = -1;
- private int _lasterr()
- {
- return errno;
- }
- }
- else
- {
- static assert(0); // No socket support yet.
- }
- version(unittest)
- {
- static assert(is(uint32_t == uint));
- static assert(is(uint16_t == ushort));
- private import std.stdio : writefln;
- // Print a message on exception instead of failing the unittest.
- private void softUnittest(void delegate() test, int line = __LINE__)
- {
- try
- test();
- catch (Throwable e)
- {
- writefln(" --- std.socket(%d) test fails depending on environment ---", line);
- writefln(" (%s)", e);
- }
- }
- }
- /// Base exception thrown by $(D std.socket).
- class SocketException: Exception
- {
- ///
- this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
- {
- super(msg, file, line, next);
- }
- ///
- this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
- {
- super(msg, next, file, line);
- }
- }
- // Needs to be public so that SocketOSException can be thrown outside of
- // std.socket (since it uses it as a default argument), but it probably doesn't
- // need to actually show up in the docs, since there's not really any public
- // need for it outside of being a default argument.
- string formatSocketError(int err)
- {
- version(Posix)
- {
- char[80] buf;
- const(char)* cs;
- version (linux)
- {
- cs = strerror_r(err, buf.ptr, buf.length);
- }
- else version (OSX)
- {
- auto errs = strerror_r(err, buf.ptr, buf.length);
- if (errs == 0)
- cs = buf.ptr;
- else
- return "Socket error " ~ to!string(err);
- }
- else version (FreeBSD)
- {
- auto errs = strerror_r(err, buf.ptr, buf.length);
- if (errs == 0)
- cs = buf.ptr;
- else
- return "Socket error " ~ to!string(err);
- }
- else
- static assert(0);
- auto len = strlen(cs);
- if(cs[len - 1] == '\n')
- len--;
- if(cs[len - 1] == '\r')
- len--;
- return cs[0 .. len].idup;
- }
- else
- version(Windows)
- {
- return sysErrorString(err);
- }
- else
- return "Socket error " ~ to!string(err);
- }
- /// Retrieve the error message for the most recently encountered network error.
- @property string lastSocketError()
- {
- return formatSocketError(_lasterr());
- }
- /// Socket exceptions representing network errors reported by the operating
- /// system.
- class SocketOSException: SocketException
- {
- 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)
- {
- errorCode = err;
- if (msg.length)
- super(msg ~ ": " ~ errorFormatter(err), file, line, next);
- else
- super(errorFormatter(err), file, line, next);
- }
- ///
- this(string msg,
- Throwable next,
- string file = __FILE__,
- size_t line = __LINE__,
- int err = _lasterr(),
- string function(int) errorFormatter = &formatSocketError)
- {
- this(msg, file, line, next, err, errorFormatter);
- }
- ///
- this(string msg,
- int err,
- string function(int) errorFormatter = &formatSocketError,
- string file = __FILE__,
- size_t line = __LINE__,
- Throwable next = null)
- {
- this(msg, file, line, next, err, errorFormatter);
- }
- }
- /// Socket exceptions representing invalid parameters specified by user code.
- class SocketParameterException: SocketException
- {
- ///
- this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
- {
- super(msg, file, line, next);
- }
- ///
- this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
- {
- super(msg, next, file, line);
- }
- }
- /// Socket exceptions representing attempts to use network capabilities not
- /// available on the current system.
- class SocketFeatureException: SocketException
- {
- ///
- this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
- {
- super(msg, file, line, next);
- }
- ///
- this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
- {
- super(msg, next, file, line);
- }
- }
- /// Return $(D true) if the last socket operation failed because the socket
- /// was in non-blocking mode and the operation would have blocked.
- bool wouldHaveBlocked()
- {
- version(Windows)
- return _lasterr() == WSAEWOULDBLOCK;
- else version(Posix)
- return _lasterr() == EAGAIN;
- else
- static assert(0);
- }
- private __gshared typeof(&getnameinfo) getnameinfoPointer;
- private __gshared typeof(&getaddrinfo) getaddrinfoPointer;
- private __gshared typeof(&freeaddrinfo) freeaddrinfoPointer;
- shared static this()
- {
- version(Windows)
- {
- WSADATA wd;
- // Winsock will still load if an older version is present.
- // The version is just a request.
- int val;
- val = WSAStartup(0x2020, &wd);
- if(val) // Request Winsock 2.2 for IPv6.
- throw new SocketOSException("Unable to initialize socket library", val);
- // These functions may not be present on older Windows versions.
- // See the comment in InternetAddress.toHostNameString() for details.
- auto ws2Lib = GetModuleHandleA("ws2_32.dll");
- if (ws2Lib)
- {
- getnameinfoPointer = cast(typeof(getnameinfoPointer))
- GetProcAddress(ws2Lib, "getnameinfo");
- getaddrinfoPointer = cast(typeof(getaddrinfoPointer))
- GetProcAddress(ws2Lib, "getaddrinfo");
- freeaddrinfoPointer = cast(typeof(freeaddrinfoPointer))
- GetProcAddress(ws2Lib, "freeaddrinfo");
- }
- }
- else version(Posix)
- {
- getnameinfoPointer = &getnameinfo;
- getaddrinfoPointer = &getaddrinfo;
- freeaddrinfoPointer = &freeaddrinfo;
- }
- }
- shared static ~this()
- {
- version(Windows)
- {
- WSACleanup();
- }
- }
- /**
- * The communication domain used to resolve an address.
- */
- enum AddressFamily: int
- {
- UNSPEC = AF_UNSPEC, /// Unspecified address family
- UNIX = AF_UNIX, /// Local communication
- INET = AF_INET, /// Internet Protocol version 4
- IPX = AF_IPX, /// Novell IPX
- APPLETALK = AF_APPLETALK, /// AppleTalk
- INET6 = AF_INET6, /// Internet Protocol version 6
- }
- /**
- * Communication semantics
- */
- enum SocketType: int
- {
- STREAM = SOCK_STREAM, /// Sequenced, reliable, two-way communication-based byte streams
- DGRAM = SOCK_DGRAM, /// Connectionless, unreliable datagrams with a fixed maximum length; data may be lost or arrive out of order
- RAW = SOCK_RAW, /// Raw protocol access
- RDM = SOCK_RDM, /// Reliably-delivered message datagrams
- SEQPACKET = SOCK_SEQPACKET, /// Sequenced, reliable, two-way connection-based datagrams with a fixed maximum length
- }
- /**
- * Protocol
- */
- enum ProtocolType: int
- {
- IP = IPPROTO_IP, /// Internet Protocol version 4
- ICMP = IPPROTO_ICMP, /// Internet Control Message Protocol
- IGMP = IPPROTO_IGMP, /// Internet Group Management Protocol
- GGP = IPPROTO_GGP, /// Gateway to Gateway Protocol
- TCP = IPPROTO_TCP, /// Transmission Control Protocol
- PUP = IPPROTO_PUP, /// PARC Universal Packet Protocol
- UDP = IPPROTO_UDP, /// User Datagram Protocol
- IDP = IPPROTO_IDP, /// Xerox NS protocol
- RAW = IPPROTO_RAW, /// Raw IP packets
- IPV6 = IPPROTO_IPV6, /// Internet Protocol version 6
- }
- /**
- * $(D 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");
- * ---
- */
- class Protocol
- {
- /// These members are populated when one of the following functions are called successfully:
- ProtocolType type;
- string name; /// ditto
- string[] aliases; /// ditto
- void populate(protoent* proto)
- {
- type = cast(ProtocolType)proto.p_proto;
- name = to!string(proto.p_name);
- int i;
- for(i = 0;; i++)
- {
- if(!proto.p_aliases[i])
- break;
- }
- if(i)
- {
- aliases = new string[i];
- for(i = 0; i != aliases.length; i++)
- {
- aliases[i] =
- to!string(proto.p_aliases[i]);
- }
- }
- else
- {
- aliases = null;
- }
- }
- /** Returns: false on failure */
- bool getProtocolByName(in char[] name)
- {
- protoent* proto;
- proto = getprotobyname(toStringz(name));
- if(!proto)
- return false;
- populate(proto);
- return true;
- }
- /** Returns: false on failure */
- // Same as getprotobynumber().
- bool getProtocolByType(ProtocolType type)
- {
- protoent* proto;
- proto = getprotobynumber(type);
- if(!proto)
- return false;
- populate(proto);
- return true;
- }
- }
- unittest
- {
- softUnittest({
- Protocol proto = new Protocol;
- assert(proto.getProtocolByType(ProtocolType.TCP));
- //writeln("About protocol TCP:");
- //writefln("\tName: %s", proto.name);
- // foreach(string s; proto.aliases)
- // {
- // writefln("\tAlias: %s", s);
- // }
- assert(proto.name == "tcp");
- assert(proto.aliases.length == 1 && proto.aliases[0] == "TCP");
- });
- }
- /**
- * $(D 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.");
- * ---
- */
- class Service
- {
- /// These members are populated when one of the following functions are called successfully:
- string name;
- string[] aliases; /// ditto
- ushort port; /// ditto
- string protocolName; /// ditto
- void populate(servent* serv)
- {
- name = to!string(serv.s_name);
- port = ntohs(cast(ushort)serv.s_port);
- protocolName = to!string(serv.s_proto);
- int i;
- for(i = 0;; i++)
- {
- if(!serv.s_aliases[i])
- break;
- }
- if(i)
- {
- aliases = new string[i];
- for(i = 0; i != aliases.length; i++)
- {
- aliases[i] =
- to!string(serv.s_aliases[i]);
- }
- }
- else
- {
- aliases = null;
- }
- }
- /**
- * If a protocol name is omitted, any protocol will be matched.
- * Returns: false on failure.
- */
- bool getServiceByName(in char[] name, in char[] protocolName = null)
- {
- servent* serv;
- serv = getservbyname(toStringz(name), protocolName !is null ? toStringz(protocolName) : null);
- if(!serv)
- return false;
- populate(serv);
- return true;
- }
- /// ditto
- bool getServiceByPort(ushort port, in char[] protocolName = null)
- {
- servent* serv;
- serv = getservbyport(port, protocolName !is null ? toStringz(protocolName) : null);
- if(!serv)
- return false;
- populate(serv);
- return true;
- }
- }
- unittest
- {
- softUnittest({
- Service serv = new Service;
- if(serv.getServiceByName("epmap", "tcp"))
- {
- // writefln("About service epmap:");
- // writefln("\tService: %s", serv.name);
- // writefln("\tPort: %d", serv.port);
- // writefln("\tProtocol: %s", serv.protocolName);
- // foreach(string s; serv.aliases)
- // {
- // writefln("\tAlias: %s", s);
- // }
- // For reasons unknown this is loc-srv on Wine and epmap on Windows
- assert(serv.name == "loc-srv" || serv.name == "epmap", serv.name);
- assert(serv.port == 135);
- assert(serv.protocolName == "tcp");
- }
- else
- {
- writefln("No service for epmap.");
- }
- });
- }
- /**
- * Class for exceptions thrown from an $(D InternetHost).
- */
- class HostException: SocketOSException
- {
- ///
- this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null, int err = _lasterr())
- {
- super(msg, file, line, next, err);
- }
- ///
- this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__, int err = _lasterr())
- {
- super(msg, next, file, line, err);
- }
- ///
- this(string msg, int err, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
- {
- super(msg, next, file, line, err);
- }
- }
- /**
- * $(D InternetHost) is a class for resolving IPv4 addresses.
- *
- * Consider using $(D getAddress), $(D parseAddress) and $(D 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");
- * ---
- */
- class InternetHost
- {
- /// These members are populated when one of the following functions are called successfully:
- string name;
- string[] aliases; /// ditto
- uint[] addrList; /// ditto
- void validHostent(hostent* he)
- {
- if(he.h_addrtype != cast(int)AddressFamily.INET || he.h_length != 4)
- throw new HostException("Address family mismatch");
- }
- void populate(hostent* he)
- {
- int i;
- char* p;
- name = to!string(he.h_name);
- for(i = 0;; i++)
- {
- p = he.h_aliases[i];
- if(!p)
- break;
- }
- if(i)
- {
- aliases = new string[i];
- for(i = 0; i != aliases.length; i++)
- {
- aliases[i] =
- to!string(he.h_aliases[i]);
- }
- }
- else
- {
- aliases = null;
- }
- for(i = 0;; i++)
- {
- p = he.h_addr_list[i];
- if(!p)
- break;
- }
- if(i)
- {
- addrList = new uint[i];
- for(i = 0; i != addrList.length; i++)
- {
- addrList[i] = ntohl(*(cast(uint*)he.h_addr_list[i]));
- }
- }
- else
- {
- addrList = null;
- }
- }
- private bool getHostNoSync(string opMixin, T)(T param)
- {
- mixin(opMixin);
- if (!he)
- return false;
- validHostent(he);
- populate(he);
- return true;
- }
- version(Windows)
- alias getHostNoSync getHost;
- else
- {
- // posix systems use global state for return value, so we
- // must synchronize across all threads
- private bool getHost(string opMixin, T)(T param)
- {
- synchronized(this.classinfo)
- return getHostNoSync!(opMixin, T)(param);
- }
- }
- /**
- * Resolve host name.
- * Returns: false if unable to resolve.
- */
- bool getHostByName(in char[] name)
- {
- static if (is(typeof(gethostbyname_r)))
- {
- return getHostNoSync!q{
- hostent he_v;
- hostent* he;
- ubyte[256] buffer_v = void;
- auto buffer = buffer_v[];
- auto param_z = std.string.toStringz(param);
- while (true)
- {
- he = &he_v;
- int errno;
- if (gethostbyname_r(param_z, he, buffer.ptr, buffer.length, &he, &errno) == ERANGE)
- buffer.length = buffer.length * 2;
- else
- break;
- }
- }(name);
- }
- else
- {
- return getHost!q{
- auto he = gethostbyname(toStringz(param));
- }(name);
- }
- }
- /**
- * Resolve IPv4 address number.
- *
- * Params:
- * addr = The IPv4 address to resolve, in host byte order.
- * Returns:
- * false if unable to resolve.
- */
- bool getHostByAddr(uint addr)
- {
- return getHost!q{
- auto x = htonl(param);
- auto he = gethostbyaddr(&x, 4, cast(int)AddressFamily.INET);
- }(addr);
- }
- /**
- * Same as previous, but addr is an IPv4 address string in the
- * dotted-decimal form $(I a.b.c.d).
- * Returns: false if unable to resolve.
- */
- bool getHostByAddr(in char[] addr)
- {
- return getHost!q{
- auto x = inet_addr(std.string.toStringz(param));
- enforce(x != INADDR_NONE,
- new SocketParameterException("Invalid IPv4 address"));
- auto he = gethostbyaddr(&x, 4, cast(int)AddressFamily.INET);
- }(addr);
- }
- }
- unittest
- {
- InternetHost ih = new InternetHost;
- ih.getHostByAddr(0x7F_00_00_01);
- assert(ih.addrList[0] == 0x7F_00_00_01);
- ih.getHostByAddr("127.0.0.1");
- assert(ih.addrList[0] == 0x7F_00_00_01);
- softUnittest({
- if (!ih.getHostByName("www.digitalmars.com"))
- return; // don't fail if not connected to internet
- //writefln("addrList.length = %d", ih.addrList.length);
- 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);
- // writefln("IP address = %s", ia.toAddrString());
- // writefln("name = %s", ih.name);
- // foreach(int i, string s; ih.aliases)
- // {
- // writefln("aliases[%d] = %s", i, s);
- // }
- // writefln("---");
- //assert(ih.getHostByAddr(ih.addrList[0]));
- // writefln("name = %s", ih.name);
- // foreach(int i, string s; ih.aliases)
- // {
- // writefln("aliases[%d] = %s", i, s);
- // }
- });
- }
- /// Holds information about a socket _address retrieved by $(D getAddressInfo).
- struct AddressInfo
- {
- AddressFamily family; /// Address _family
- SocketType type; /// Socket _type
- ProtocolType protocol; /// Protocol
- Address address; /// Socket _address
- string canonicalName; /// Canonical name, when $(D AddressInfoFlags.CANONNAME) is used.
- }
- // A subset of flags supported on all platforms with getaddrinfo.
- /// Specifies option flags for $(D getAddressInfo).
- enum AddressInfoFlags: int
- {
- /// The resulting addresses will be used in a call to $(D Socket.bind).
- PASSIVE = AI_PASSIVE,
- /// The canonical name is returned in $(D canonicalName) member in the first $(D AddressInfo).
- CANONNAME = AI_CANONNAME,
- /// The $(D node) parameter passed to $(D getAddressInfo) must be a numeric string.
- /// This will suppress any potentially lengthy network host address lookups.
- NUMERICHOST = AI_NUMERICHOST,
- }
- /// On POSIX, getaddrinfo uses its own error codes, and thus has its own
- /// formatting function.
- private string formatGaiError(int err)
- {
- version(Windows)
- {
- return sysErrorString(err);
- }
- else
- {
- synchronized
- return to!string(gai_strerror(err));
- }
- }
- /**
- * Provides _protocol-independent translation from host names to socket
- * addresses. If advanced functionality is not required, consider using
- * $(D getAddress) for compatibility with older systems.
- *
- * Returns: Array with one $(D AddressInfo) per socket address.
- *
- * Throws: $(D SocketOSException) on failure, or $(D SocketFeatureException)
- * if this functionality is not available on the current system.
- *
- * Params:
- * node = string containing host name or numeric address
- * options = optional additional parameters, identified by type:
- * $(UL $(LI $(D string) - service name or port number)
- * $(LI $(D AddressInfoFlags) - option flags)
- * $(LI $(D AddressFamily) - address family to filter by)
- * $(LI $(D SocketType) - socket type to filter by)
- * $(LI $(D 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);
- * ---
- */
- AddressInfo[] getAddressInfo(T...)(in char[] node, T options)
- {
- const(char)[] service = null;
- addrinfo hints;
- hints.ai_family = AF_UNSPEC;
- foreach (option; options)
- {
- static if (is(typeof(option) : const(char)[]))
- service = option;
- else
- static if (is(typeof(option) == AddressInfoFlags))
- hints.ai_flags |= option;
- else
- static if (is(typeof(option) == AddressFamily))
- hints.ai_family = option;
- else
- static if (is(typeof(option) == SocketType))
- hints.ai_socktype = option;
- else
- static if (is(typeof(option) == ProtocolType))
- hints.ai_protocol = option;
- else
- static assert(0, "Unknown getAddressInfo option type: " ~ typeof(option).stringof);
- }
- return getAddressInfoImpl(node, service, &hints);
- }
- private AddressInfo[] getAddressInfoImpl(in char[] node, in char[] service, addrinfo* hints)
- {
- if (getaddrinfoPointer && freeaddrinfoPointer)
- {
- addrinfo* ai_res;
- int ret = getaddrinfoPointer(
- node is null ? null : std.string.toStringz(node),
- service is null ? null : std.string.toStringz(service),
- hints, &ai_res);
- scope(exit) if (ai_res) freeaddrinfoPointer(ai_res);
- enforce(ret == 0, new SocketOSException("getaddrinfo error", ret, &formatGaiError));
- AddressInfo[] result;
- // Use const to force UnknownAddressReference to copy the sockaddr.
- for (const(addrinfo)* ai = ai_res; ai; ai = ai.ai_next)
- result ~= AddressInfo(
- cast(AddressFamily) ai.ai_family,
- cast(SocketType ) ai.ai_socktype,
- cast(ProtocolType ) ai.ai_protocol,
- new UnknownAddressReference(ai.ai_addr, cast(socklen_t) ai.ai_addrlen),
- ai.ai_canonname ? to!string(ai.ai_canonname) : null);
- assert(result.length > 0);
- return result;
- }
- throw new SocketFeatureException("Address info lookup is not available " ~
- "on this system.");
- }
- unittest
- {
- softUnittest({
- if (getaddrinfoPointer)
- {
- // 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);
- }
- });
- }
- private ushort serviceToPort(in char[] service)
- {
- if (service == "")
- return InternetAddress.PORT_ANY;
- else
- if (isNumeric(service))
- return to!ushort(service);
- else
- {
- auto s = new Service();
- s.getServiceByName(service);
- return s.port;
- }
- }
- /**
- * Provides _protocol-independent translation from host names to socket
- * addresses. Uses $(D getAddressInfo) if the current system supports it,
- * and $(D InternetHost) otherwise.
- *
- * Returns: Array with one $(D Address) instance per socket address.
- *
- * Throws: $(D 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[] getAddress(in char[] hostname, in char[] service = null)
- {
- if (getaddrinfoPointer && freeaddrinfoPointer)
- {
- // use getAddressInfo
- Address[] results;
- auto infos = getAddressInfo(hostname, service);
- foreach (ref info; infos)
- results ~= info.address;
- return results;
- }
- else
- return getAddress(hostname, serviceToPort(service));
- }
- /// ditto
- Address[] getAddress(in char[] hostname, ushort port)
- {
- if (getaddrinfoPointer && freeaddrinfoPointer)
- return getAddress(hostname, to!string(port));
- else
- {
- // use getHostByName
- auto ih = new InternetHost;
- if (!ih.getHostByName(hostname))
- throw new AddressException(
- text("Unable to resolve host '", hostname, "'"));
- Address[] results;
- foreach (uint addr; ih.addrList)
- results ~= new InternetAddress(addr, port);
- return results;
- }
- }
- unittest
- {
- softUnittest({
- auto addresses = getAddress("63.105.9.61");
- assert(addresses.length && addresses[0].toAddrString() == "63.105.9.61");
- if (getaddrinfoPointer)
- {
- // test via gethostbyname
- auto getaddrinfoPointerBackup = getaddrinfoPointer;
- getaddrinfoPointer = null;
- scope(exit) getaddrinfoPointer = getaddrinfoPointerBackup;
- addresses = getAddress("63.105.9.61");
- assert(addresses.length && addresses[0].toAddrString() == "63.105.9.61");
- }
- });
- }
- /**
- * Provides _protocol-independent parsing of network addresses. Does not
- * attempt name resolution. Uses $(D getAddressInfo) with
- * $(D AddressInfoFlags.NUMERICHOST) if the current system supports it, and
- * $(D InternetAddress) otherwise.
- *
- * Returns: An $(D Address) instance representing specified address.
- *
- * Throws: $(D 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);
- * }
- * ---
- */
- Address parseAddress(in char[] hostaddr, in char[] service = null)
- {
- if (getaddrinfoPointer && freeaddrinfoPointer)
- return getAddressInfo(hostaddr, service, AddressInfoFlags.NUMERICHOST)[0].address;
- else
- return parseAddress(hostaddr, serviceToPort(service));
- }
- /// ditto
- Address parseAddress(in char[] hostaddr, ushort port)
- {
- if (getaddrinfoPointer && freeaddrinfoPointer)
- return parseAddress(hostaddr, to!string(port));
- else
- {
- auto in4_addr = InternetAddress.parse(hostaddr);
- enforce(in4_addr != InternetAddress.ADDR_NONE,
- new SocketParameterException("Invalid IP address"));
- return new InternetAddress(in4_addr, port);
- }
- }
- unittest
- {
- softUnittest({
- auto address = parseAddress("63.105.9.61");
- assert(address.toAddrString() == "63.105.9.61");
- if (getaddrinfoPointer)
- {
- // test via inet_addr
- auto getaddrinfoPointerBackup = getaddrinfoPointer;
- getaddrinfoPointer = null;
- scope(exit) getaddrinfoPointer = getaddrinfoPointerBackup;
- address = parseAddress("63.105.9.61");
- assert(address.toAddrString() == "63.105.9.61");
- }
- assert(collectException!SocketException(parseAddress("Invalid IP address")));
- });
- }
- /**
- * Class for exceptions thrown from an $(D Address).
- */
- class AddressException: SocketOSException
- {
- ///
- this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null, int err = _lasterr())
- {
- super(msg, file, line, next, err);
- }
- ///
- this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__, int err = _lasterr())
- {
- super(msg, next, file, line, err);
- }
- ///
- this(string msg, int err, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
- {
- super(msg, next, file, line, err);
- }
- }
- /**
- * $(D 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 class Address
- {
- /// Returns pointer to underlying $(D sockaddr) structure.
- abstract @property sockaddr* name();
- abstract @property const(sockaddr)* name() const; /// ditto
- /// Returns actual size of underlying $(D sockaddr) structure.
- abstract @property socklen_t nameLen() const;
- /// Family of this address.
- @property AddressFamily addressFamily() const
- {
- return cast(AddressFamily) name.sa_family;
- }
- // Common code for toAddrString and toHostNameString
- private final string toHostString(bool numeric) const
- {
- // getnameinfo() is the recommended way to perform a reverse (name)
- // lookup on both Posix and Windows. However, it is only available
- // on Windows XP and above, and not included with the WinSock import
- // libraries shipped with DMD. Thus, we check for getnameinfo at
- // runtime in the shared module constructor, and use it if it's
- // available in the base class method. Classes for specific network
- // families (e.g. InternetHost) override this method and use a
- // deprecated, albeit commonly-available method when getnameinfo()
- // is not available.
- // http://technet.microsoft.com/en-us/library/aa450403.aspx
- if (getnameinfoPointer)
- {
- auto buf = new char[NI_MAXHOST];
- auto ret = getnameinfoPointer(
- name, nameLen,
- buf.ptr, cast(uint)buf.length,
- null, 0,
- numeric ? NI_NUMERICHOST : NI_NAMEREQD);
- if (!numeric)
- {
- if (ret==EAI_NONAME)
- return null;
- version(Windows)
- if (ret==WSANO_DATA)
- return null;
- }
- enforce(ret == 0, new AddressException("Could not get " ~
- (numeric ? "host address" : "host name")));
- return assumeUnique(buf[0 .. strlen(buf.ptr)]);
- }
- throw new SocketFeatureException((numeric ? "Host address" : "Host name") ~
- " lookup for this address family is not available on this system.");
- }
- // Common code for toPortString and toServiceNameString
- private final string toServiceString(bool numeric) const
- {
- // See toHostNameString() for details about getnameinfo().
- if (getnameinfoPointer)
- {
- auto buf = new char[NI_MAXSERV];
- enforce(getnameinfoPointer(
- name, nameLen,
- null, 0,
- buf.ptr, cast(uint)buf.length,
- numeric ? NI_NUMERICSERV : NI_NAMEREQD
- ) == 0, new AddressException("Could not get " ~
- (numeric ? "port number" : "service name")));
- return assumeUnique(buf[0 .. strlen(buf.ptr)]);
- }
- throw new SocketFeatureException((numeric ? "Port number" : "Service name") ~
- " lookup for this address family is not available on this system.");
- }
- /**
- * Attempts to retrieve the host address as a human-readable string.
- *
- * Throws: $(D AddressException) on failure, or $(D SocketFeatureException)
- * if address retrieval for this address family is not available on the
- * current system.
- */
- string toAddrString() const
- {
- return toHostString(true);
- }
- /**
- * Attempts to retrieve the host name as a fully qualified domain name.
- *
- * Returns: The FQDN corresponding to this $(D Address), or $(D null) if
- * the host name did not resolve.
- *
- * Throws: $(D AddressException) on error, or $(D SocketFeatureException)
- * if host name lookup for this address family is not available on the
- * current system.
- */
- string toHostNameString() const
- {
- return toHostString(false);
- }
- /**
- * Attempts to retrieve the numeric port number as a string.
- *
- * Throws: $(D AddressException) on failure, or $(D SocketFeatureException)
- * if port number retrieval for this address family is not available on the
- * current system.
- */
- string toPortString() const
- {
- return toServiceString(true);
- }
- /**
- * Attempts to retrieve the service name as a string.
- *
- * Throws: $(D AddressException) on failure, or $(D SocketFeatureException)
- * if service name lookup for this address family is not available on the
- * current system.
- */
- string toServiceNameString() const
- {
- return toServiceString(false);
- }
- /// Human readable string representing this address.
- override string toString() const
- {
- try
- {
- string host = toAddrString();
- string port = toPortString();
- if (host.indexOf(':') >= 0)
- return "[" ~ host ~ "]:" ~ port;
- else
- return host ~ ":" ~ port;
- }
- catch (SocketException)
- return "Unknown";
- }
- }
- /**
- * $(D UnknownAddress) encapsulates an unknown socket address.
- */
- class UnknownAddress: Address
- {
- protected:
- sockaddr sa;
- public:
- override @property sockaddr* name()
- {
- return &sa;
- }
- override @property const(sockaddr)* name() const
- {
- return &sa;
- }
- override @property socklen_t nameLen() const
- {
- return cast(socklen_t) sa.sizeof;
- }
- }
- /**
- * $(D UnknownAddressReference) encapsulates a reference to an arbitrary
- * socket address.
- */
- class UnknownAddressReference: Address
- {
- protected:
- sockaddr* sa;
- socklen_t len;
- public:
- /// Constructs an $(D Address) with a reference to the specified $(D sockaddr).
- this(sockaddr* sa, socklen_t len)
- {
- this.sa = sa;
- this.len = len;
- }
- /// Constructs an $(D Address) with a copy of the specified $(D sockaddr).
- this(const(sockaddr)* sa, socklen_t len)
- {
- this.sa = cast(sockaddr*) (cast(ubyte*)sa)[0..len].dup.ptr;
- this.len = len;
- }
- override @property sockaddr* name()
- {
- return sa;
- }
- override @property const(sockaddr)* name() const
- {
- return sa;
- }
- override @property socklen_t nameLen() const
- {
- return cast(socklen_t) len;
- }
- }
- /**
- * $(D InternetAddress) encapsulates an IPv4 (Internet Protocol version 4)
- * socket address.
- *
- * Consider using $(D getAddress), $(D parseAddress) and $(D Address) methods
- * instead of using this class directly.
- */
- class InternetAddress: Address
- {
- protected:
- sockaddr_in sin;
- this()
- {
- }
- public:
- override @property sockaddr* name()
- {
- return cast(sockaddr*)&sin;
- }
- override @property const(sockaddr)* name() const
- {
- return cast(const(sockaddr)*)&sin;
- }
- override @property socklen_t nameLen() const
- {
- return cast(socklen_t) sin.sizeof;
- }
- enum uint ADDR_ANY = INADDR_ANY; /// Any IPv4 host address.
- enum uint ADDR_NONE = INADDR_NONE; /// An invalid IPv4 host address.
- enum ushort PORT_ANY = 0; /// Any IPv4 port number.
- /// Returns the IPv4 _port number (in host byte order).
- @property ushort port() const
- {
- return ntohs(sin.sin_port);
- }
- /// Returns the IPv4 address number (in host byte order).
- @property uint addr() const
- {
- return ntohl(sin.sin_addr.s_addr);
- }
- /**
- * Construct a new $(D InternetAddress).
- * Params:
- * addr = an IPv4 address string in the dotted-decimal form a.b.c.d,
- * or a host name which will be resolved using an $(D InternetHost)
- * object.
- * port = port number, may be $(D PORT_ANY).
- */
- this(in char[] addr, ushort port)
- {
- uint uiaddr = parse(addr);
- if(ADDR_NONE == uiaddr)
- {
- InternetHost ih = new InternetHost;
- if(!ih.getHostByName(addr))
- //throw new AddressException("Invalid internet address");
- throw new AddressException(
- text("Unable to resolve host '", addr, "'"));
- uiaddr = ih.addrList[0];
- }
- sin.sin_family = AddressFamily.INET;
- sin.sin_addr.s_addr = htonl(uiaddr);
- sin.sin_port = htons(port);
- }
- /**
- * Construct a new $(D InternetAddress).
- * Params:
- * addr = (optional) an IPv4 address in host byte order, may be $(D ADDR_ANY).
- * port = port number, may be $(D PORT_ANY).
- */
- this(uint addr, ushort port)
- {
- sin.sin_family = AddressFamily.INET;
- sin.sin_addr.s_addr = htonl(addr);
- sin.sin_port = htons(port);
- }
- /// ditto
- this(ushort port)
- {
- sin.sin_family = AddressFamily.INET;
- sin.sin_addr.s_addr = ADDR_ANY;
- sin.sin_port = htons(port);
- }
- /// Human readable string representing the IPv4 address in dotted-decimal form.
- override string toAddrString() const
- {
- return to!string(inet_ntoa(sin.sin_addr));
- }
- /// Human readable string representing the IPv4 port.
- override string toPortString() const
- {
- return std.conv.to!string(port);
- }
- /**
- * Attempts to retrieve the host name as a fully qualified domain name.
- *
- * Returns: The FQDN corresponding to this $(D InternetAddress), or
- * $(D null) if the host name did not resolve.
- *
- * Throws: $(D AddressException) on error.
- */
- override string toHostNameString() const
- {
- // getnameinfo() is the recommended way to perform a reverse (name)
- // lookup on both Posix and Windows. However, it is only available
- // on Windows XP and above, and not included with the WinSock import
- // libraries shipped with DMD. Thus, we check for getnameinfo at
- // runtime in the shared module constructor, and fall back to the
- // deprecated getHostByAddr() if it could not be found. See also:
- // http://technet.microsoft.com/en-us/library/aa450403.aspx
- if (getnameinfoPointer)
- return super.toHostNameString();
- else
- {
- auto host = new InternetHost();
- if (!host.getHostByAddr(ntohl(sin.sin_addr.s_addr)))
- return null;
- return host.name;
- }
- }
- /**
- * Parse an IPv4 address string in the dotted-decimal form $(I a.b.c.d)
- * and return the number.
- * Returns: If the string is not a legitimate IPv4 address,
- * $(D ADDR_NONE) is returned.
- */
- static uint parse(in char[] addr)
- {
- return ntohl(inet_addr(std.string.toStringz(addr)));
- }
- /**
- * Convert an IPv4 address number in host byte order to a human readable
- * string representing the IPv4 address in dotted-decimal form.
- */
- static string addrToString(uint addr)
- {
- in_addr sin_addr;
- sin_addr.s_addr = htonl(addr);
- return to!string(inet_ntoa(sin_addr));
- }
- }
- unittest
- {
- softUnittest({
- const InternetAddress ia = new InternetAddress("63.105.9.61", 80);
- assert(ia.toString() == "63.105.9.61:80");
- });
- softUnittest({
- // test reverse lookup
- auto ih = new InternetHost;
- if (ih.getHostByName("digitalmars.com"))
- {
- const ia = new InternetAddress(ih.addrList[0], 80);
- assert(ia.toHostNameString() == "digitalmars.com");
- if (getnameinfoPointer)
- {
- // test reverse lookup, via gethostbyaddr
- auto getnameinfoPointerBackup = getnameinfoPointer;
- getnameinfoPointer = null;
- scope(exit) getnameinfoPointer = getnameinfoPointerBackup;
- assert(ia.toHostNameString() == "digitalmars.com");
- }
- }
- });
- version (SlowTests)
- softUnittest({
- // test failing reverse lookup
- const InternetAddress ia = new InternetAddress("127.114.111.120", 80);
- assert(ia.toHostNameString() is null);
- if (getnameinfoPointer)
- {
- // test failing reverse lookup, via gethostbyaddr
- auto getnameinfoPointerBackup = getnameinfoPointer;
- getnameinfoPointer = null;
- scope(exit) getnameinfoPointer = getnameinfoPointerBackup;
- assert(ia.toHostNameString() is null);
- }
- });
- }
- /**
- * $(D Internet6Address) encapsulates an IPv6 (Internet Protocol version 6)
- * socket address.
- *
- * Consider using $(D getAddress), $(D parseAddress) and $(D Address) methods
- * instead of using this class directly.
- */
- class Internet6Address: Address
- {
- protected:
- sockaddr_in6 sin6;
- this()
- {
- }
- public:
- override @property sockaddr* name()
- {
- return cast(sockaddr*)&sin6;
- }
- override @property const(sockaddr)* name() const
- {
- return cast(const(sockaddr)*)&sin6;
- }
- override @property socklen_t nameLen() const
- {
- return cast(socklen_t) sin6.sizeof;
- }
- /// Any IPv6 host address.
- static @property ref const(ubyte)[16] ADDR_ANY()
- {
- const(ubyte)[16]* addr;
- static if (is(typeof(IN6ADDR_ANY)))
- return addr = &IN6ADDR_ANY.s6_addr, *addr;
- else
- static if (is(typeof(in6addr_any)))
- return addr = &i…