D Programming Language 2.0

- Comments
- D
- Search
- Home

Last update Mon Oct 24 15:54:50 2011

# std.socket

Notes:
For Win32 systems, link with ws2_32.lib.

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

Authors:
Christopher E. Miller, David Nadlinger

Source:
std/socket.d

class SocketException: object.Exception;
  Base exception thrown from a Socket.

  int errorCode;
    Platform-specific error code.

enum AddressFamily;
  The communication domain used to resolve an address.

  UNSPEC

  UNIX
    local communication

  INET
    internet protocol version 4

  IPX
    novell IPX

  APPLETALK
    appletalk

enum SocketType;
  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;
  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

  IPV6
    internet protocol version 6

class Protocol;
  Protocol is a class for retrieving protocol information.

  ProtocolType type;
  string name;
  string[] aliases;
    These members are populated when one of the following functions are called without failure:

  bool getProtocolByName(string name);
    Returns false on failure

  bool getProtocolByType(ProtocolType type);
    Returns false on failure

class Service;
  Service is a class for retrieving service information.

  string name;
  string[] aliases;
  ushort port;
  string protocolName;
    These members are populated when one of the following functions are called without failure:

  bool getServiceByName(string name, string protocolName);
  bool getServiceByName(string name);
  bool getServiceByPort(ushort port, string protocolName);
  bool getServiceByPort(ushort port);
    If a protocol name is omitted, any protocol will be matched.

    Returns:
    false on failure.

class HostException: object.Exception;
  Base exception thrown from an InternetHost.

  int errorCode;
    Platform-specific error code.

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

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

  bool getHostByName(string name);
    Resolve host name. Returns false if unable to resolve.

  bool getHostByAddr(uint addr);
    Resolve IPv4 address number. Returns false if unable to resolve.

    Parameters:

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

  bool getHostByAddr(string 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.

class AddressException: object.Exception;
  Base exception thrown from an Address.

abstract class Address;
  Address is an abstract class for representing a network addresses.

  AddressFamily addressFamily();
    Family of this address.

  string toString();
    Human readable string representing this address.

class UnknownAddress: std.socket.Address;

class InternetAddress: std.socket.Address;
  InternetAddress is a class that represents an IPv4 (internet protocol version 4) address and port.

  uint ADDR_ANY;
    Any IPv4 address number.

  uint ADDR_NONE;
    An invalid IPv4 address number.

  ushort PORT_ANY;
    Any IPv4 port number.

  AddressFamily addressFamily();
    Overridden to return AddressFamily.INET.

  ushort port();
    Returns the IPv4 port number.

  uint addr();
    Returns the IPv4 address number.

  this(string addr, ushort port);
    Parameters:

    string addr | an IPv4 address string in the dotted-decimal form a.b.c.d, or a host name that will be resolved using an InternetHost object.
    ushort port | may be PORT_ANY as stated below.

  this(uint addr, ushort port);
  this(ushort port);
    Construct a new Address. addr may be ADDR_ANY (default) and port may be PORT_ANY, and the actual numbers may not be known until a connection is made.

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

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

  string toString();
    Human readable string representing the IPv4 address and port in the form a.b.c.d:e.

  static uint parse(string addr);
    Parse an IPv4 address string in the dotted-decimal form a.b.c.d and return the number. If the string is not a legitimate IPv4 address, ADDR_NONE is returned.

class SocketAcceptException: std.socket.SocketException;

enum SocketShutdown;
  How a socket is shutdown:

  RECEIVE
    socket receives are disallowed

  SEND
    socket sends are disallowed

  BOTH
    both RECEIVE and SEND

enum SocketFlags;
  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.

  c_long seconds;
    Number of seconds.

  c_long microseconds;
    Number of additional microseconds.

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

  this(uint max);
    Set the maximum amount of sockets that may be added.

  this();
    Uses the default maximum for the system.

  void reset();
    Reset the SocketSet so that there are 0 Sockets in the collection.

  void add(Socket s);
    Add a Socket to the collection. Adding more than the maximum has dangerous side affects.

  void remove(Socket s);
    Remove this Socket from the collection.

  int isSet(Socket s);
    Returns nonzero if this Socket is in the collection.

  uint max();
    Return maximum amount of sockets that can be added, like FD_SETSIZE.

enum SocketOptionLevel;
  The level at which a socket option is defined:

  SOCKET
    socket level

  IP
    internet protocol version 4 level

  ICMP

  IGMP

  GGP

  TCP
    transmission control protocol level

  PUP

  UDP
    user datagram protocol level

  IDP

  IPV6
    internet protocol version 6 level

struct linger;
  Linger information for use with SocketOption.LINGER.

  uint16_t on;
    Nonzero for on.

  uint16_t time;
    Linger time.

enum SocketOption;
  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

  TCP_NODELAY
    disable the Nagle algorithm for send coalescing

  IPV6_UNICAST_HOPS

  IPV6_MULTICAST_IF

  IPV6_MULTICAST_LOOP

  IPV6_JOIN_GROUP

  IPV6_LEAVE_GROUP

class Socket;
  Socket is a class that creates a network communication endpoint using the Berkeley sockets interface.

  this(AddressFamily af, SocketType type, ProtocolType protocol);
  this(AddressFamily af, SocketType type);
  this(AddressFamily af, SocketType type, string 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.

  socket_t handle();
    Get underlying socket handle.

  bool blocking();
  void blocking(bool byes);
    Get/set socket's blocking flag.

    When a socket is blocking, calls to receive(), accept(), and send() will block and wait for data/action. A non-blocking socket will immediately return instead of blocking.

  AddressFamily addressFamily();
    Get the socket's address family.

  bool isAlive();
    Property that indicates if this is a valid, alive socket.

  void bind(Address addr);
    Associate a local address with this socket.

  void connect(Address to);
    Establish a connection. If the socket is blocking, connect waits for the connection to be made. If the socket is nonblocking, connect returns immediately and the connection attempt is still in progress.

  void listen(int backlog);
    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.

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

  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.

  void shutdown(SocketShutdown how);
    Disables sends and/or receives.

  void close();
    Immediately drop any connections and release socket resources. Calling shutdown before close is recommended for connection-oriented sockets. The Socket object is no longer usable after close.

  static string hostName();
    Returns the local machine's host name. Idea from mango.

  Address remoteAddress();
    Remote endpoint Address.

  Address localAddress();
    Local endpoint Address.

  int ERROR;
    Send or receive error code.

  Select!(false,long,int) send(const(void)[] buf, SocketFlags flags);
  Select!(false,long,int) send(const(void)[] buf);
    Send data on the connection. Returns the number of bytes actually sent, or ERROR on failure. If the socket is blocking and there is no buffer space left, send waits.

  Select!(false,long,int) sendTo(const(void)[] buf, SocketFlags flags, Address to);
  Select!(false,long,int) sendTo(const(void)[] buf, Address to);
  Select!(false,long,int) sendTo(const(void)[] buf, SocketFlags flags);
  Select!(false,long,int) sendTo(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.

  ptrdiff_t receive(void[] buf, SocketFlags flags);
  ptrdiff_t receive(void[] buf);
    Receive data on the connection. Returns the number of bytes actually received, 0 if the remote side has closed the connection, or ERROR on failure. If the socket is blocking, receive waits until there is data to be received.

  Select!(false,long,int) receiveFrom(void[] buf, SocketFlags flags, out Address from);
  ptrdiff_t receiveFrom(void[] buf, out Address from);
  Select!(false,long,int) receiveFrom(void[] buf, SocketFlags flags);
  ptrdiff_t receiveFrom(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 ERROR on failure.

  int getOption(SocketOptionLevel level, SocketOption option, void[] result);
    Get a socket option. Returns the number of bytes written to result.

  int getOption(SocketOptionLevel level, SocketOption option, out int32_t result);
    Common case of getting integer and boolean options.

  int getOption(SocketOptionLevel level, SocketOption option, out linger result);
    Get the linger option.

  void getOption(SocketOptionLevel level, SocketOption option, out Duration result);
    Get a timeout (duration) option.

  void setOption(SocketOptionLevel level, SocketOption option, int32_t value);
    Common case for setting integer and boolean options.

  void setOption(SocketOptionLevel level, SocketOption option, linger value);
    Set the linger option.

  void setOption(SocketOptionLevel level, SocketOption option, Duration value);
    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:

    Duration value | The timeout duration to set. Must not be negative.

    Throws:
    SocketException if setting the options fails.

    Example:

         import std.datetime;
         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(AutoStart.yes);
         ubyte[1] buffer;
         pair[0].receive(buffer);
         writefln("Waited %s ms until the socket timed out.",
             sw.peek.msecs);

  static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, timeval* tv);
  static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, int microseconds);
  static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError);
    Wait for a socket to change status. A wait timeout timeval or int microseconds 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.

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 TCP Socket.

  this(Address connectTo);
    Constructs a blocking TCP Socket and connects to an InternetAddress.

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 UDP Socket.

Socket[2u] 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);

Copyright © 1999-2011 by Digital Mars, All Rights Reserved | Page generated by Ddoc.