network-2.8.0.1: Low-level networking interface

Copyright | (c) The University of Glasgow 2001
License | BSD-style (see the file libraries/network/LICENSE)
Maintainer | libraries@haskell.org
Stability | provisional
Portability | portable
Safe Haskell | None
Language | Haskell98

Network.Socket

Contents

- Initialisation
- Address information
  - Types
  - Flags
- Socket operations
  - Closing
- Socket options
- Socket
  - Types of Socket
  - Family
  - Protocol number
- Socket address
  - Host address
  - Host address6
  - Flow Info
  - Scope ID
  - Port number
- UNIX-domain socket
- Name information
- Low level operations
- Sending and receiving data
- Special constants
- Deprecated
  - Deprecated sending and receiving
  - Deprecated address functions
  - Deprecated socket operations
  - Deprecated socket status
  - Deprecated special constants
  - Decrecated internal functions
  - Decrecated UNIX-domain functions
- Orphan instances

Description

This is the main module of the network package supposed to be used with either Network.Socket.ByteString or Network.Socket.ByteString.Lazy for sending/receiving.

Here are two minimal example programs using the TCP/IP protocol: a server that echoes all data that it receives back (servicing only one client) and a client using it.

    -- Echo server program
    module Main (main) where

    import Control.Concurrent (forkFinally)
    import qualified Control.Exception as E
    import Control.Monad (unless, forever, void)
    import qualified Data.ByteString as S
    import Network.Socket hiding (recv)
    import Network.Socket.ByteString (recv, sendAll)

    main :: IO ()
    main = withSocketsDo $ do
        addr <- resolve "3000"
        E.bracket (open addr) close loop
      where
        resolve port = do
            let hints = defaultHints {
                    addrFlags = [AI_PASSIVE]
                  , addrSocketType = Stream
                  }
            addr:_ <- getAddrInfo (Just hints) Nothing (Just port)
            return addr
        open addr = do
            sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
            setSocketOption sock ReuseAddr 1
            bind sock (addrAddress addr)
            -- If the prefork technique is not used,
            -- set CloseOnExec for the security reasons.
            let fd = fdSocket sock
            setCloseOnExecIfNeeded fd
            listen sock 10
            return sock
        loop sock = forever $ do
            (conn, peer) <- accept sock
            putStrLn $ "Connection from " ++ show peer
            void $ forkFinally (talk conn) (\_ -> close conn)
        talk conn = do
            msg <- recv conn 1024
            unless (S.null msg) $ do
              sendAll conn msg
              talk conn

    {-# LANGUAGE OverloadedStrings #-}
    -- Echo client program
    module Main (main) where

    import qualified Control.Exception as E
    import qualified Data.ByteString.Char8 as C
    import Network.Socket hiding (recv)
    import Network.Socket.ByteString (recv, sendAll)

    main :: IO ()
    main = withSocketsDo $ do
        addr <- resolve "127.0.0.1" "3000"
        E.bracket (open addr) close talk
      where
        resolve host port = do
            let hints = defaultHints { addrSocketType = Stream }
            addr:_ <- getAddrInfo (Just hints) (Just host) (Just port)
            return addr
        open addr = do
            sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
            connect sock $ addrAddress addr
            return sock
        talk sock = do
            sendAll sock "Hello, world!"
            msg <- recv sock 1024
            putStr "Received: "
            C.putStrLn msg

The proper programming model is that one `Socket` is handled by a single thread. If multiple threads use one `Socket` concurrently, unexpected things would happen. There is one exception for multiple threads vs a single `Socket`: one thread reads data from a `Socket` only and the other thread writes data to the `Socket` only.

Synopsis

- withSocketsDo :: IO a -> IO a
- getAddrInfo :: Maybe AddrInfo -> Maybe HostName -> Maybe ServiceName -> IO [AddrInfo]
- type HostName = String
- type ServiceName = String
- data AddrInfo = AddrInfo {
  - addrFlags :: [AddrInfoFlag]
  - addrFamily :: Family
  - addrSocketType :: SocketType
  - addrProtocol :: ProtocolNumber
  - addrAddress :: SockAddr
  - addrCanonName :: Maybe String
  }
- defaultHints :: AddrInfo
- data AddrInfoFlag
  - = AI_ADDRCONFIG
  - | AI_ALL
  - | AI_CANONNAME
  - | AI_NUMERICHOST
  - | AI_NUMERICSERV
  - | AI_PASSIVE
  - | AI_V4MAPPED
- addrInfoFlagImplemented :: AddrInfoFlag -> Bool
- connect :: Socket -> SockAddr -> IO ()
- bind :: Socket -> SockAddr -> IO ()
- listen :: Socket -> Int -> IO ()
- accept :: Socket -> IO (Socket, SockAddr)
- close :: Socket -> IO ()
- close' :: Socket -> IO ()
- shutdown :: Socket -> ShutdownCmd -> IO ()
- data ShutdownCmd
  - = ShutdownReceive
  - | ShutdownSend
  - | ShutdownBoth
- data SocketOption
  - = Debug
  - | ReuseAddr
  - | Type
  - | SoError
  - | DontRoute
  - | Broadcast
  - | SendBuffer
  - | RecvBuffer
  - | KeepAlive
  - | OOBInline
  - | TimeToLive
  - | MaxSegment
  - | NoDelay
  - | Cork
  - | Linger
  - | ReusePort
  - | RecvLowWater
  - | SendLowWater
  - | RecvTimeOut
  - | SendTimeOut
  - | UseLoopBack
  - | UserTimeout
  - | IPv6Only
  - | CustomSockOpt (CInt, CInt)
- isSupportedSocketOption :: SocketOption -> Bool
- getSocketOption :: Socket -> SocketOption -> IO Int
- setSocketOption :: Socket -> SocketOption -> Int -> IO ()
- data Socket = MkSocket CInt Family SocketType ProtocolNumber (MVar SocketStatus)
- socket :: Family -> SocketType -> ProtocolNumber -> IO Socket
- fdSocket :: Socket -> CInt
- mkSocket :: CInt -> Family -> SocketType -> ProtocolNumber -> SocketStatus -> IO Socket
- socketToHandle :: Socket -> IOMode -> IO Handle
- data SocketType
  - = NoSocketType
  - | Stream
  - | Datagram
  - | Raw
  - | RDM
  - | SeqPacket
- isSupportedSocketType :: SocketType -> Bool
- data Family
  - = AF_UNSPEC
  - | AF_UNIX
  - | AF_INET
  - | AF_INET6
  - | AF_IMPLINK
  - | AF_PUP
  - | AF_CHAOS
  - | AF_NS
  - | AF_NBS
  - | AF_ECMA
  - | AF_DATAKIT
  - | AF_CCITT
  - | AF_SNA
  - | AF_DECnet
  - | AF_DLI
  - | AF_LAT
  - | AF_HYLINK
  - | AF_APPLETALK
  - | AF_ROUTE
  - | AF_NETBIOS
  - | AF_NIT
  - | AF_802
  - | AF_ISO
  - | AF_OSI
  - | AF_NETMAN
  - | AF_X25
  - | AF_AX25
  - | AF_OSINET
  - | AF_GOSSIP
  - | AF_IPX
  - | Pseudo_AF_XTP
  - | AF_CTF
  - | AF_WAN
  - | AF_SDL
  - | AF_NETWARE
  - | AF_NDD
  - | AF_INTF
  - | AF_COIP
  - | AF_CNT
  - | Pseudo_AF_RTIP
  - | Pseudo_AF_PIP
  - | AF_SIP
  - | AF_ISDN
  - | Pseudo_AF_KEY
  - | AF_NATM
  - | AF_ARP
  - | Pseudo_AF_HDRCMPLT
  - | AF_ENCAP
  - | AF_LINK
  - | AF_RAW
  - | AF_RIF
  - | AF_NETROM
  - | AF_BRIDGE
  - | AF_ATMPVC
  - | AF_ROSE
  - | AF_NETBEUI
  - | AF_SECURITY
  - | AF_PACKET
  - | AF_ASH
  - | AF_ECONET
  - | AF_ATMSVC
  - | AF_IRDA
  - | AF_PPPOX
  - | AF_WANPIPE
  - | AF_BLUETOOTH
  - | AF_CAN
- isSupportedFamily :: Family -> Bool
- type ProtocolNumber = CInt
- defaultProtocol :: ProtocolNumber
- data SockAddr
  - = SockAddrInet PortNumber HostAddress
  - | SockAddrInet6 PortNumber FlowInfo HostAddress6 ScopeID
  - | SockAddrUnix String
  - | SockAddrCan Int32
- isSupportedSockAddr :: SockAddr -> Bool
- getPeerName :: Socket -> IO SockAddr
- getSocketName :: Socket -> IO SockAddr
- type HostAddress = Word32
- hostAddressToTuple :: HostAddress -> (Word8, Word8, Word8, Word8)
- tupleToHostAddress :: (Word8, Word8, Word8, Word8) -> HostAddress
- type HostAddress6 = (Word32, Word32, Word32, Word32)
- hostAddress6ToTuple :: HostAddress6 -> (Word16, Word16, Word16, Word16, Word16, Word16, Word16, Word16)
- tupleToHostAddress6 :: (Word16, Word16, Word16, Word16, Word16, Word16, Word16, Word16) -> HostAddress6
- type FlowInfo = Word32
- type ScopeID = Word32
- ifNameToIndex :: String -> IO (Maybe Int)
- ifIndexToName :: Int -> IO (Maybe String)
- data PortNumber
- defaultPort :: PortNumber
- socketPortSafe :: Socket -> IO (Maybe PortNumber)
- socketPort :: Socket -> IO PortNumber
- isUnixDomainSocketAvailable :: Bool
- socketPair :: Family -> SocketType -> ProtocolNumber -> IO (Socket, Socket)
- sendFd :: Socket -> CInt -> IO ()
- recvFd :: Socket -> IO CInt
- getPeerCredential :: Socket -> IO (Maybe CUInt, Maybe CUInt, Maybe CUInt)
- data NameInfoFlag
  - = NI_DGRAM
  - | NI_NAMEREQD
  - | NI_NOFQDN
  - | NI_NUMERICHOST
  - | NI_NUMERICSERV
- getNameInfo :: [NameInfoFlag] -> Bool -> Bool -> SockAddr -> IO (Maybe HostName, Maybe ServiceName)
- setCloseOnExecIfNeeded :: CInt -> IO ()
- getCloseOnExec :: CInt -> IO Bool
- setNonBlockIfNeeded :: CInt -> IO ()
- getNonBlock :: CInt -> IO Bool
- sendBuf :: Socket -> Ptr Word8 -> Int -> IO Int
- recvBuf :: Socket -> Ptr Word8 -> Int -> IO Int
- sendBufTo :: Socket -> Ptr a -> Int -> SockAddr -> IO Int
- recvBufFrom :: Socket -> Ptr a -> Int -> IO (Int, SockAddr)
- maxListenQueue :: Int
- send :: Socket -> String -> IO Int
- sendTo :: Socket -> String -> SockAddr -> IO Int
- recv :: Socket -> Int -> IO String
- recvFrom :: Socket -> Int -> IO (String, Int, SockAddr)
- recvLen :: Socket -> Int -> IO (String, Int)
- htonl :: Word32 -> Word32
- ntohl :: Word32 -> Word32
- inet_addr :: String -> IO HostAddress
- inet_ntoa :: HostAddress -> IO String
- bindSocket :: Socket -> SockAddr -> IO ()
- sClose :: Socket -> IO ()
- data SocketStatus
  - = NotConnected
  - | Bound
  - | Listening
  - | Connected
  - | ConvertedToHandle
  - | Closed
- isConnected :: Socket -> IO Bool
- isBound :: Socket -> IO Bool
- isListening :: Socket -> IO Bool
- isReadable :: Socket -> IO Bool
- isWritable :: Socket -> IO Bool
- sIsConnected :: Socket -> IO Bool
- sIsBound :: Socket -> IO Bool
- sIsListening :: Socket -> IO Bool
- sIsReadable :: Socket -> IO Bool
- sIsWritable :: Socket -> IO Bool
- aNY_PORT :: PortNumber
- iNADDR_ANY :: HostAddress
- iN6ADDR_ANY :: HostAddress6
- sOMAXCONN :: Int
- sOL_SOCKET :: Int
- sCM_RIGHTS :: Int
- packFamily :: Family -> CInt
- unpackFamily :: CInt -> Family
- packSocketType :: SocketType -> CInt
- getPeerCred :: Socket -> IO (CUInt, CUInt, CUInt)

# Initialisation

withSocketsDo :: IO a -> IO a Source #

With older versions of the `network` library (version 2.6.0.2 or earlier) on Windows operating systems, the networking subsystem must be initialised using `withSocketsDo` before any networking operations can be used. eg.

    main = withSocketsDo $ do {...}

It is fine to nest calls to `withSocketsDo`, and to perform networking operations after `withSocketsDo` has returned.

In newer versions of the `network` library (version v2.6.1.0 or later) it is only necessary to call `withSocketsDo` if you are calling the `MkSocket` constructor directly. However, for compatibility with older versions on Windows, it is good practice to always call `withSocketsDo` (it's very cheap).

# Address information

getAddrInfo Source #

Arguments

:: Maybe AddrInfo | preferred socket type or protocol
-> Maybe HostName | host name to look up
-> Maybe ServiceName | service name to look up
-> IO [AddrInfo] | resolved addresses, with "best" first

Resolve a host or service name to one or more addresses. The `AddrInfo` values that this function returns contain `SockAddr` values that you can pass directly to `connect` or `bind`.

This function is protocol independent. It can return both IPv4 and IPv6 address information.

The `AddrInfo` argument specifies the preferred query behaviour, socket options, or protocol. You can override these conveniently using Haskell's record update syntax on `defaultHints`, for example as follows:

    >>> let hints = defaultHints { addrFlags = [AI_NUMERICHOST], addrSocketType = Stream }

You must provide a `Just` value for at least one of the `HostName` or `ServiceName` arguments. `HostName` can be either a numeric network address (dotted quad for IPv4, colon-separated hex for IPv6) or a hostname. In the latter case, its addresses will be looked up unless `AI_NUMERICHOST` is specified as a hint. If you do not provide a `HostName` value and do not set `AI_PASSIVE` as a hint, network addresses in the result will contain the address of the loopback interface.

If the query fails, this function throws an IO exception instead of returning an empty list. Otherwise, it returns a non-empty list of `AddrInfo` values.

There are several reasons why a query might result in several values. For example, the queried-for host could be multihomed, or the service might be available via several protocols.

Note: the order of arguments is slightly different to that defined for `getaddrinfo` in RFC 2553. The `AddrInfo` parameter comes first to make partial application easier.

    >>> addr:_ <- getAddrInfo (Just hints) (Just "127.0.0.1") (Just "http")
    >>> addrAddress addr
    127.0.0.1:80

## Types

type HostName = String Source #

Either a host name e.g., `"haskell.org"` or a numeric host address string consisting of a dotted decimal IPv4 address or an IPv6 address e.g., `"192.168.0.1"`.

type ServiceName = String Source #

data AddrInfo Source #

Constructors

AddrInfo |

Fields

- addrFlags :: [AddrInfoFlag]
- addrFamily :: Family
- addrSocketType :: SocketType
- addrProtocol :: ProtocolNumber
- addrAddress :: SockAddr
- addrCanonName :: Maybe String

Instances

Eq AddrInfo Source # |
Instance details Defined in Network.Socket Methods (==) :: AddrInfo -> AddrInfo -> Bool Source # (/=) :: AddrInfo -> AddrInfo -> Bool Source #
Show AddrInfo Source # |
Instance details Defined in Network.Socket Methods showsPrec :: Int -> AddrInfo -> ShowS Source # show :: AddrInfo -> String Source # showList :: [AddrInfo] -> ShowS Source #
Storable AddrInfo Source # |

Instance details

Defined in Network.Socket

Methods

sizeOf :: AddrInfo -> Int Source #

alignment :: AddrInfo -> Int Source #

peekElemOff :: Ptr AddrInfo -> Int -> IO AddrInfo Source #

pokeElemOff :: Ptr AddrInfo -> Int -> AddrInfo -> IO () Source #

peekByteOff :: Ptr b -> Int -> IO AddrInfo Source #

pokeByteOff :: Ptr b -> Int -> AddrInfo -> IO () Source #

peek :: Ptr AddrInfo -> IO AddrInfo Source #

poke :: Ptr AddrInfo -> AddrInfo -> IO () Source #

defaultHints :: AddrInfo Source #

Default hints for address lookup with `getAddrInfo`. The values of the `addrAddress` and `addrCanonName` fields are `undefined`, and are never inspected by `getAddrInfo`.

    >>> addrFlags defaultHints
    []
    >>> addrFamily defaultHints
    AF_UNSPEC
    >>> addrSocketType defaultHints
    NoSocketType
    >>> addrProtocol defaultHints
    0

## Flags

data AddrInfoFlag Source #

Flags that control the querying behaviour of `getAddrInfo`. For more information, see https://tools.ietf.org/html/rfc3493#page-25

Constructors

AI_ADDRCONFIG | The list of returned `AddrInfo` values will only contain IPv4 addresses if the local system has at least one IPv4 interface configured, and likewise for IPv6. (Only some platforms support this.)
AI_ALL | If `AI_ALL` is specified, return all matching IPv6 and IPv4 addresses. Otherwise, this flag has no effect. (Only some platforms support this.)
AI_CANONNAME | The `addrCanonName` field of the first returned `AddrInfo` will contain the "canonical name" of the host.
AI_NUMERICHOST | The `HostName` argument must be a numeric address in string form, and network name lookups will not be attempted.
AI_NUMERICSERV | The `ServiceName` argument must be a port number in string form, and service name lookups will not be attempted. (Only some platforms support this.)
AI_PASSIVE | If no `HostName` value is provided, the network address in each `SockAddr` will be left as a "wild card". This is useful for server applications that will accept connections from any client.
AI_V4MAPPED | If an IPv6 lookup is performed, and no IPv6 addresses are found, IPv6-mapped IPv4 addresses will be returned. (Only some platforms support this.)

Instances

Eq AddrInfoFlag Source # |
Instance details Defined in Network.Socket Methods (==) :: AddrInfoFlag -> AddrInfoFlag -> Bool Source # (/=) :: AddrInfoFlag -> AddrInfoFlag -> Bool Source #
Read AddrInfoFlag Source # |
Instance details Defined in Network.Socket Methods readsPrec :: Int -> ReadS AddrInfoFlag Source # readList :: ReadS [AddrInfoFlag] Source # readPrec :: ReadPrec AddrInfoFlag Source # readListPrec :: ReadPrec [AddrInfoFlag] Source #
Show AddrInfoFlag Source # |
Instance details Defined in Network.Socket Methods showsPrec :: Int -> AddrInfoFlag -> ShowS Source # show :: AddrInfoFlag -> String Source # showList :: [AddrInfoFlag] -> ShowS Source #

addrInfoFlagImplemented :: AddrInfoFlag -> Bool Source #

Indicate whether the given `AddrInfoFlag` will have any effect on this system.

# Socket operations

connect :: Socket -> SockAddr -> IO () Source #

Connect to a remote socket at address.

bind :: Socket -> SockAddr -> IO () Source #

Bind the socket to an address. The socket must not already be bound. The `Family` passed to `bind` must be the same as that passed to `socket`. If the special port number `defaultPort` is passed then the system assigns the next available use port.

listen :: Socket -> Int -> IO () Source #

Listen for connections made to the socket. The second argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5).

accept :: Socket -> IO (Socket, SockAddr) Source #

Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair `(conn, address)` where `conn` is a new socket object usable to send and receive data on the connection, and `address` is the address bound to the socket on the other end of the connection.

## Closing

close :: Socket -> IO () Source #

Close the socket. This function does not throw exceptions even if the underlying system call returns errors.

Sending data to or receiving data from closed socket may lead to undefined behaviour.

If multiple threads use the same socket and one uses `fdSocket` and the other use `close`, unexpected behavior may happen. For more information, please refer to the documentation of `fdSocket`.

close' :: Socket -> IO () Source #

Close the socket. This function throws exceptions if the underlying system call returns errors.

Sending data to or receiving data from closed socket may lead to undefined behaviour.

shutdown :: Socket -> ShutdownCmd -> IO () Source #

Shut down one or both halves of the connection, depending on the second argument to the function. If the second argument is `ShutdownReceive`, further receives are disallowed. If it is `ShutdownSend`, further sends are disallowed. If it is `ShutdownBoth`, further sends and receives are disallowed.

data ShutdownCmd Source #

Constructors

ShutdownReceive |
ShutdownSend |
ShutdownBoth |

# Socket options

data SocketOption Source #

Socket options for use with `setSocketOption` and `getSocketOption`.

The existence of a constructor does not imply that the relevant option is supported on your system: see `isSupportedSocketOption`

Constructors

Debug | SO_DEBUG
ReuseAddr | SO_REUSEADDR
Type | SO_TYPE
SoError | SO_ERROR
DontRoute | SO_DONTROUTE
Broadcast | SO_BROADCAST
SendBuffer | SO_SNDBUF
RecvBuffer | SO_RCVBUF
KeepAlive | SO_KEEPALIVE
OOBInline | SO_OOBINLINE
TimeToLive | IP_TTL
MaxSegment | TCP_MAXSEG
NoDelay | TCP_NODELAY
Cork | TCP_CORK
Linger | SO_LINGER
ReusePort | SO_REUSEPORT
RecvLowWater | SO_RCVLOWAT
SendLowWater | SO_SNDLOWAT
RecvTimeOut | SO_RCVTIMEO
SendTimeOut | SO_SNDTIMEO
UseLoopBack | SO_USELOOPBACK
UserTimeout | TCP_USER_TIMEOUT
IPv6Only | IPV6_V6ONLY
CustomSockOpt (CInt, CInt) |

Instances

Show SocketOption Source # |
Instance details Defined in Network.Socket Methods showsPrec :: Int -> SocketOption -> ShowS Source # show :: SocketOption -> String Source # showList :: [SocketOption] -> ShowS Source #

isSupportedSocketOption :: SocketOption -> Bool Source #

Does the `SocketOption` exist on this system?

getSocketOption :: Socket -> SocketOption -> IO Int Source #

Get a socket option that gives an Int value. There is currently no API to get e.g. the timeval socket options

setSocketOption :: Socket -> SocketOption -> Int -> IO () Source #

Set a socket option that expects an Int value. There is currently no API to set e.g. the timeval socket options

# Socket

data Socket Source #

A socket data type. `Socket`s are not GCed unless they are closed by `close`.

Constructors

MkSocket CInt Family SocketType ProtocolNumber (MVar SocketStatus) | Deprecated: `MkSocket` will not be available in version 3.0.0.0 or later. Use fdSocket instead

Instances

Eq Socket Source # |
Instance details Defined in Network.Socket.Types Methods (==) :: Socket -> Socket -> Bool Source # (/=) :: Socket -> Socket -> Bool Source #
Show Socket Source # |
Instance details Defined in Network.Socket.Types Methods showsPrec :: Int -> Socket -> ShowS Source # show :: Socket -> String Source # showList :: [Socket] -> ShowS Source #

socket :: Family -> SocketType -> ProtocolNumber -> IO Socket Source #

Create a new socket using the given address family, socket type and protocol number. The address family is usually `AF_INET`, `AF_INET6`, or `AF_UNIX`. The socket type is usually `Stream` or `Datagram`. The protocol number is usually `defaultProtocol`. If `AF_INET6` is used and the socket type is `Stream` or `Datagram`, the `IPv6Only` socket option is set to 0 so that both IPv4 and IPv6 can be handled with one socket.

    >>> let hints = defaultHints { addrFlags = [AI_NUMERICHOST, AI_NUMERICSERV], addrSocketType = Stream }
    >>> addr:_ <- getAddrInfo (Just hints) (Just "127.0.0.1") (Just "5000")
    >>> sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
    >>> bind sock (addrAddress addr)
    >>> getSocketName sock
    127.0.0.1:5000

fdSocket :: Socket -> CInt Source #

Obtaining the file descriptor from a socket.

If a `Socket` is shared with multiple threads and one uses `fdSocket`, unexpected issues may happen. Consider the following scenario:

1) Thread A acquires a `Fd` from `Socket` by `fdSocket`.

2) Thread B close the `Socket`.

3) Thread C opens a new `Socket`. Unfortunately it gets the same `Fd` number which thread A is holding.

In this case, it is safer for Thread A to clone `Fd` by `dup`. But this would still suffer from a rase condition between `fdSocket` and `close`.

mkSocket :: CInt -> Family -> SocketType -> ProtocolNumber -> SocketStatus -> IO Socket Source #

Smart constructor for constructing a `Socket`. It should only be called once for every new file descriptor. The caller must make sure that the socket is in non-blocking mode. See `setNonBlockIfNeeded`.

socketToHandle :: Socket -> IOMode -> IO Handle Source #

Turns a Socket into an `Handle`. By default, the new handle is unbuffered. Use `hSetBuffering` to change the buffering.

Note that since a `Handle` is automatically closed by a finalizer when it is no longer referenced, you should avoid doing any more operations on the `Socket` after calling `socketToHandle`. To close the `Socket` after `socketToHandle`, call `hClose` on the `Handle`.

## Types of Socket

data SocketType Source #

Socket Types.

The existence of a constructor does not necessarily imply that that socket type is supported on your system: see `isSupportedSocketType`.

Constructors

NoSocketType | 0, used in getAddrInfo hints, for example
Stream | SOCK_STREAM
Datagram | SOCK_DGRAM
Raw | SOCK_RAW
RDM | SOCK_RDM
SeqPacket | SOCK_SEQPACKET

Instances

Eq SocketType Source # |
Instance details Defined in Network.Socket.Types Methods (==) :: SocketType -> SocketType -> Bool Source # (/=) :: SocketType -> SocketType -> Bool Source #
Ord SocketType Source # |

Instance details

Defined in Network.Socket.Types

Methods

compare :: SocketType -> SocketType -> Ordering Source #

(<) :: SocketType -> SocketType -> Bool Source #

(<=) :: SocketType -> SocketType -> Bool Source #

(>) :: SocketType -> SocketType -> Bool Source #

(>=) :: SocketType -> SocketType -> Bool Source #

max :: SocketType -> SocketType -> SocketType Source #

min :: SocketType -> SocketType -> SocketType Source #

Read SocketType Source # |
Instance details Defined in Network.Socket.Types Methods readsPrec :: Int -> ReadS SocketType Source # readList :: ReadS [SocketType] Source # readPrec :: ReadPrec SocketType Source # readListPrec :: ReadPrec [SocketType] Source #
Show SocketType Source # |
Instance details Defined in Network.Socket.Types Methods showsPrec :: Int -> SocketType -> ShowS Source # show :: SocketType -> String Source # showList :: [SocketType] -> ShowS Source #

isSupportedSocketType :: SocketType -> Bool Source #

Does the SOCK_ constant corresponding to the given SocketType exist on this system?

## Family

data Family Source #

Address families.

A constructor being present here does not mean it is supported by the operating system: see `isSupportedFamily`.

Constructors

AF_UNSPEC |
AF_UNIX |
AF_INET |
AF_INET6 |
AF_IMPLINK |
AF_PUP |
AF_CHAOS |
AF_NS |
AF_NBS |
AF_ECMA |
AF_DATAKIT |
AF_CCITT |
AF_SNA |
AF_DECnet |
AF_DLI |
AF_LAT |
AF_HYLINK |
AF_APPLETALK |
AF_ROUTE |
AF_NETBIOS |
AF_NIT |
AF_802 |
AF_ISO |
AF_OSI |
AF_NETMAN |
AF_X25 |
AF_AX25 |
AF_OSINET |
AF_GOSSIP |
AF_IPX |
Pseudo_AF_XTP |
AF_CTF |
AF_WAN |
AF_SDL |
AF_NETWARE |
AF_NDD |
AF_INTF |
AF_COIP |
AF_CNT |
Pseudo_AF_RTIP |
Pseudo_AF_PIP |
AF_SIP |
AF_ISDN |
Pseudo_AF_KEY |
AF_NATM |
AF_ARP |
Pseudo_AF_HDRCMPLT |
AF_ENCAP |
AF_LINK |
AF_RAW |
AF_RIF |
AF_NETROM |
AF_BRIDGE |
AF_ATMPVC |
AF_ROSE |
AF_NETBEUI |
AF_SECURITY |
AF_PACKET |
AF_ASH |
AF_ECONET |
AF_ATMSVC |
AF_IRDA |
AF_PPPOX |
AF_WANPIPE |
AF_BLUETOOTH |
AF_CAN |

Instances

Eq Family Source # |
Instance details Defined in Network.Socket.Types Methods (==) :: Family -> Family -> Bool Source # (/=) :: Family -> Family -> Bool Source #
Ord Family Source # |
Instance details Defined in Network.Socket.Types Methods compare :: Family -> Family -> Ordering Source # (<) :: Family -> Family -> Bool Source # (<=) :: Family -> Family -> Bool Source # (>) :: Family -> Family -> Bool Source # (>=) :: Family -> Family -> Bool Source # max :: Family -> Family -> Family Source # min :: Family -> Family -> Family Source #
Read Family Source # |
Instance details Defined in Network.Socket.Types Methods readsPrec :: Int -> ReadS Family Source # readList :: ReadS [Family] Source # readPrec :: ReadPrec Family Source # readListPrec :: ReadPrec [Family] Source #
Show Family Source # |
Instance details Defined in Network.Socket.Types Methods showsPrec :: Int -> Family -> ShowS Source # show :: Family -> String Source # showList :: [Family] -> ShowS Source #

isSupportedFamily :: Family -> Bool Source #

Does the AF_ constant corresponding to the given family exist on this system?

## Protocol number

type ProtocolNumber = CInt Source #

defaultProtocol :: ProtocolNumber Source #

This is the default protocol for a given service.

# Socket address

data SockAddr Source #

The existence of a constructor does not necessarily imply that that socket address type is supported on your system: see `isSupportedSockAddr`.

Constructors

SockAddrInet PortNumber HostAddress |
SockAddrInet6 PortNumber FlowInfo HostAddress6 ScopeID |
SockAddrUnix String |
SockAddrCan Int32 | Deprecated: This will be removed in 3.0

Instances

Eq SockAddr Source # |
Instance details Defined in Network.Socket.Types Methods (==) :: SockAddr -> SockAddr -> Bool Source # (/=) :: SockAddr -> SockAddr -> Bool Source #
Ord SockAddr Source # |
Instance details Defined in Network.Socket.Types Methods compare :: SockAddr -> SockAddr -> Ordering Source # (<) :: SockAddr -> SockAddr -> Bool Source # (<=) :: SockAddr -> SockAddr -> Bool Source # (>) :: SockAddr -> SockAddr -> Bool Source # (>=) :: SockAddr -> SockAddr -> Bool Source # max :: SockAddr -> SockAddr -> SockAddr Source # min :: SockAddr -> SockAddr -> SockAddr Source #
Show SockAddr Source # |
Instance details Defined in Network.Socket Methods showsPrec :: Int -> SockAddr -> ShowS Source # show :: SockAddr -> String Source # showList :: [SockAddr] -> ShowS Source #

isSupportedSockAddr :: SockAddr -> Bool Source #

Is the socket address type supported on this system?

getPeerName :: Socket -> IO SockAddr Source #

getSocketName :: Socket -> IO SockAddr Source #

## Host address

type HostAddress = Word32 Source #

The raw network byte order number is read using host byte order. Therefore on little-endian architectures the byte order is swapped. For example `127.0.0.1` is represented as `0x0100007f` on little-endian hosts and as `0x7f000001` on big-endian hosts.

For direct manipulation prefer `hostAddressToTuple` and `tupleToHostAddress`.

hostAddressToTuple :: HostAddress -> (Word8, Word8, Word8, Word8) Source #

Converts `HostAddress` to representation-independent IPv4 quadruple. For example for `127.0.0.1` the function will return `(0x7f, 0, 0, 1)` regardless of host endianness.

tupleToHostAddress :: (Word8, Word8, Word8, Word8) -> HostAddress Source #

Converts IPv4 quadruple to `HostAddress`.

## Host address6

type HostAddress6 = (Word32, Word32, Word32, Word32) Source #

Independent of endianness. For example `::1` is stored as `(0, 0, 0, 1)`.

For direct manipulation prefer `hostAddress6ToTuple` and `tupleToHostAddress6`.

hostAddress6ToTuple :: HostAddress6 -> (Word16, Word16, Word16, Word16, Word16, Word16, Word16, Word16) Source #

tupleToHostAddress6 :: (Word16, Word16, Word16, Word16, Word16, Word16, Word16, Word16) -> HostAddress6 Source #

## Flow Info

type FlowInfo = Word32 Source #

## Scope ID

type ScopeID = Word32 Source #

ifNameToIndex :: String -> IO (Maybe Int) Source #

Returns the index corresponding to the interface name.

Since 2.7.0.0.

ifIndexToName :: Int -> IO (Maybe String) Source #

Returns the interface name corresponding to the index.

Since 2.7.0.0.

## Port number

data PortNumber Source #

Use the `Num` instance (i.e. use a literal) to create a `PortNumber` value.

    >>> 1 :: PortNumber
    1
    >>> read "1" :: PortNumber
    1
    >>> show (12345 :: PortNumber)
    "12345"
    >>> 50000 < (51000 :: PortNumber)
    True
    >>> 50000 < (52000 :: PortNumber)
    True
    >>> 50000 + (10000 :: PortNumber)
    60000

Instances

Enum PortNumber Source # |

Instance details

Defined in Network.Socket.Types

Methods

succ :: PortNumber -> PortNumber Source #

pred :: PortNumber -> PortNumber Source #

toEnum :: Int -> PortNumber Source #

fromEnum :: PortNumber -> Int Source #

enumFrom :: PortNumber -> [PortNumber] Source #

enumFromThen :: PortNumber -> PortNumber -> [PortNumber] Source #

enumFromTo :: PortNumber -> PortNumber -> [PortNumber] Source #

enumFromThenTo :: PortNumber -> PortNumber -> PortNumber -> [PortNumber] Source #

Eq PortNumber Source # |
Instance details Defined in Network.Socket.Types Methods (==) :: PortNumber -> PortNumber -> Bool Source # (/=) :: PortNumber -> PortNumber -> Bool Source #
Integral PortNumber Source # |

Instance details

Defined in Network.Socket.Types

Methods

quot :: PortNumber -> PortNumber -> PortNumber Source #

rem :: PortNumber -> PortNumber -> PortNumber Source #

div :: PortNumber -> PortNumber -> PortNumber Source #

mod :: PortNumber -> PortNumber -> PortNumber Source #

quotRem :: PortNumber -> PortNumber -> (PortNumber, PortNumber) Source #

divMod :: PortNumber -> PortNumber -> (PortNumber, PortNumber) Source #

toInteger :: PortNumber -> Integer Source #

Num PortNumber Source # |
Instance details Defined in Network.Socket.Types Methods (+) :: PortNumber -> PortNumber -> PortNumber Source # (-) :: PortNumber -> PortNumber -> PortNumber Source # (*) :: PortNumber -> PortNumber -> PortNumber Source # negate :: PortNumber -> PortNumber Source # abs :: PortNumber -> PortNumber Source # signum :: PortNumber -> PortNumber Source # fromInteger :: Integer -> PortNumber Source #
Ord PortNumber Source # |

Instance details

Defined in Network.Socket.Types

Methods

compare :: PortNumber -> PortNumber -> Ordering Source #

(<) :: PortNumber -> PortNumber -> Bool Source #

(<=) :: PortNumber -> PortNumber -> Bool Source #

(>) :: PortNumber -> PortNumber -> Bool Source #

(>=) :: PortNumber -> PortNumber -> Bool Source #

max :: PortNumber -> PortNumber -> PortNumber Source #

min :: PortNumber -> PortNumber -> PortNumber Source #

Read PortNumber Source # |
Instance details Defined in Network.Socket.Types Methods readsPrec :: Int -> ReadS PortNumber Source # readList :: ReadS [PortNumber] Source # readPrec :: ReadPrec PortNumber Source # readListPrec :: ReadPrec [PortNumber] Source #
Real PortNumber Source # |
Instance details Defined in Network.Socket.Types Methods toRational :: PortNumber -> Rational Source #
Show PortNumber Source # |
Instance details Defined in Network.Socket.Types Methods showsPrec :: Int -> PortNumber -> ShowS Source # show :: PortNumber -> String Source # showList :: [PortNumber] -> ShowS Source #
Storable PortNumber Source # |

Instance details

Defined in Network.Socket.Types

Methods

sizeOf :: PortNumber -> Int Source #

alignment :: PortNumber -> Int Source #

peekElemOff :: Ptr PortNumber -> Int -> IO PortNumber Source #

pokeElemOff :: Ptr PortNumber -> Int -> PortNumber -> IO () Source #

peekByteOff :: Ptr b -> Int -> IO PortNumber Source #

pokeByteOff :: Ptr b -> Int -> PortNumber -> IO () Source #

peek :: Ptr PortNumber -> IO PortNumber Source #

poke :: Ptr PortNumber -> PortNumber -> IO () Source #

defaultPort :: PortNumber Source #

socketPortSafe :: Socket -> IO (Maybe PortNumber) Source #

Getting the port of socket.

socketPort :: Socket -> IO PortNumber Source #

Getting the port of socket. `IOError` is thrown if a port is not available.

# UNIX-domain socket

isUnixDomainSocketAvailable :: Bool Source #

Whether or not UNIX-domain sockets are available.

Since 3.0.0.0.

socketPair :: Family -> SocketType -> ProtocolNumber -> IO (Socket, Socket) Source #

Build a pair of connected socket objects using the given address family, socket type, and protocol number. Address family, socket type, and protocol number are as for the `socket` function above. Availability: Unix.

sendFd :: Socket -> CInt -> IO () Source #

recvFd :: Socket -> IO CInt Source #

Receive a file descriptor over a domain socket. Note that the resulting file descriptor may have to be put into non-blocking mode in order to be used safely. See `setNonBlockIfNeeded`.

getPeerCredential :: Socket -> IO (Maybe CUInt, Maybe CUInt, Maybe CUInt) Source #

Getting process ID, user ID and group ID for UNIX-domain sockets.

This is implemented with SO_PEERCRED on Linux and getpeereid() on BSD variants. Unfortunately, on some BSD variants getpeereid() returns unexpected results, rather than an error, for AF_INET sockets. It is the user's responsibility to make sure that the socket is a UNIX-domain socket. Also, on some BSD variants, getpeereid() does not return credentials for sockets created via `socketPair`, only separately created and then explicitly connected UNIX-domain sockets work on such systems.

Since 2.7.0.0.

# Name information

data NameInfoFlag Source #

Flags that control the querying behaviour of `getNameInfo`. For more information, see https://tools.ietf.org/html/rfc3493#page-30

Constructors

NI_DGRAM | Resolve a datagram-based service name. This is required only for the few protocols that have different port numbers for their datagram-based versions than for their stream-based versions.
NI_NAMEREQD | If the hostname cannot be looked up, an IO error is thrown.
NI_NOFQDN | If a host is local, return only the hostname part of the FQDN.
NI_NUMERICHOST | The name of the host is not looked up. Instead, a numeric representation of the host's address is returned. For an IPv4 address, this will be a dotted-quad string. For IPv6, it will be colon-separated hexadecimal.
NI_NUMERICSERV | The name of the service is not looked up. Instead, a numeric representation of the service is returned.

Instances

Eq NameInfoFlag Source # |
Instance details Defined in Network.Socket Methods (==) :: NameInfoFlag -> NameInfoFlag -> Bool Source # (/=) :: NameInfoFlag -> NameInfoFlag -> Bool Source #
Read NameInfoFlag Source # |
Instance details Defined in Network.Socket Methods readsPrec :: Int -> ReadS NameInfoFlag Source # readList :: ReadS [NameInfoFlag] Source # readPrec :: ReadPrec NameInfoFlag Source # readListPrec :: ReadPrec [NameInfoFlag] Source #
Show NameInfoFlag Source # |
Instance details Defined in Network.Socket Methods showsPrec :: Int -> NameInfoFlag -> ShowS Source # show :: NameInfoFlag -> String Source # showList :: [NameInfoFlag] -> ShowS Source #

getNameInfo Source #

Arguments

:: [NameInfoFlag] | flags to control lookup behaviour
-> Bool | whether to look up a hostname
-> Bool | whether to look up a service name
-> SockAddr | the address to look up
-> IO (Maybe HostName, Maybe ServiceName) |

Resolve an address to a host or service name. This function is protocol independent. The list of `NameInfoFlag` values controls query behaviour.

If a host or service's name cannot be looked up, then the numeric form of the address or service will be returned.

If the query fails, this function throws an IO exception.

Example: `(hostName, _) <- getNameInfo [] True False myAddress`

# Low level operations

setCloseOnExecIfNeeded :: CInt -> IO () Source #

Set the close_on_exec flag on Unix. On Windows, nothing is done.

Since 2.7.0.0.

getCloseOnExec :: CInt -> IO Bool Source #

Get the nonblocking flag. On Windows, this function always returns `False`.

Since 2.7.0.0.

setNonBlockIfNeeded :: CInt -> IO () Source #

Set the nonblocking flag on Unix. On Windows, nothing is done.

getNonBlock :: CInt -> IO Bool Source #

Get the close_on_exec flag. On Windows, this function always returns `False`.

Since 2.7.0.0.

# Sending and receiving data

sendBuf :: Socket -> Ptr Word8 -> Int -> IO Int Source #

Send data to the socket. The socket must be connected to a remote socket. Returns the number of bytes sent. Applications are responsible for ensuring that all data has been sent.

Sending data to closed socket may lead to undefined behaviour.

recvBuf :: Socket -> Ptr Word8 -> Int -> IO Int Source #

Receive data from the socket. The socket must be in a connected state. This function may return fewer bytes than specified. If the message is longer than the specified length, it may be discarded depending on the type of socket. This function may block until a message arrives.

Considering hardware and network realities, the maximum number of bytes to receive should be a small power of 2, e.g., 4096.

For TCP sockets, a zero length return value means the peer has closed its half side of the connection.

Receiving data from closed socket may lead to undefined behaviour.

sendBufTo :: Socket -> Ptr a -> Int -> SockAddr -> IO Int Source #

Send data to the socket. The recipient can be specified explicitly, so the socket need not be in a connected state. Returns the number of bytes sent. Applications are responsible for ensuring that all data has been sent.

recvBufFrom :: Socket -> Ptr a -> Int -> IO (Int, SockAddr) Source #

Receive data from the socket, writing it into buffer instead of creating a new string. The socket need not be in a connected state. Returns `(nbytes, address)` where `nbytes` is the number of bytes received and `address` is a `SockAddr` representing the address of the sending socket.

NOTE: blocking on Windows unless you compile with -threaded (see GHC ticket #1129)

# Special constants

maxListenQueue :: Int Source #

This is the value of SOMAXCONN, typically 128. 128 is good enough for normal network servers but is too small for high performance servers.

# Deprecated

## Deprecated sending and receiving

send :: Socket -> String -> IO Int Source #

Deprecated: Use send defined in Network.Socket.ByteString

Send data to the socket. The socket must be connected to a remote socket. Returns the number of bytes sent. Applications are responsible for ensuring that all data has been sent.

Sending data to closed socket may lead to undefined behaviour.

sendTo :: Socket -> String -> SockAddr -> IO Int Source #

Deprecated: Use sendTo defined in Network.Socket.ByteString

Send data to the socket. The recipient can be specified explicitly, so the socket need not be in a connected state. Returns the number of bytes sent. Applications are responsible for ensuring that all data has been sent.

NOTE: blocking on Windows unless you compile with -threaded (see GHC ticket #1129)

recv :: Socket -> Int -> IO String Source #

Deprecated: Use recv defined in Network.Socket.ByteString

Receive data from the socket. The socket must be in a connected state. This function may return fewer bytes than specified. If the message is longer than the specified length, it may be discarded depending on the type of socket. This function may block until a message arrives.

Considering hardware and network realities, the maximum number of bytes to receive should be a small power of 2, e.g., 4096.

For TCP sockets, a zero length return value means the peer has closed its half side of the connection.

Receiving data from closed socket may lead to undefined behaviour.

recvFrom :: Socket -> Int -> IO (String, Int, SockAddr) Source #

Deprecated: Use recvFrom defined in Network.Socket.ByteString

Receive data from the socket. The socket need not be in a connected state. Returns `(bytes, nbytes, address)` where `bytes` is a `String` of length `nbytes` representing the data received and `address` is a `SockAddr` representing the address of the sending socket.

NOTE: blocking on Windows unless you compile with -threaded (see GHC ticket #1129)

recvLen :: Socket -> Int -> IO (String, Int) Source #

Deprecated: Use recv defined in Network.Socket.ByteString with "Data.Bytestring.length"

## Deprecated address functions

htonl :: Word32 -> Word32 Source #

Deprecated: Use getAddrInfo instead

Converts the from host byte order to network byte order.

ntohl :: Word32 -> Word32 Source #

Deprecated: Use getAddrInfo instead

Converts the from network byte order to host byte order.

inet_addr :: String -> IO HostAddress Source #

Deprecated: Use "getAddrInfo" instead

inet_ntoa :: HostAddress -> IO String Source #

Deprecated: Use "getNameInfo" instead

## Deprecated socket operations

bindSocket :: Socket -> SockAddr -> IO () Source #

Deprecated: use `bind`

Deprecated alias for `bind`.

sClose :: Socket -> IO () Source #

Deprecated: use `close`

Deprecated alias for `close`.

## Deprecated socket status

data SocketStatus Source #

Deprecated: SocketStatus will be removed

The status of the socket as determined by this library, not necessarily reflecting the state of the connection itself.

For example, the `Closed` status is applied when the `close` function is called.

Constructors

NotConnected | Newly created, unconnected socket
Bound | Bound, via `bind`
Listening | Listening, via `listen`
Connected | Connected or accepted, via `connect` or `accept`
ConvertedToHandle | Is now a `Handle` (via `socketToHandle`), don't touch
Closed | Closed was closed by `close`

Instances

Eq SocketStatus Source # |
Instance details Defined in Network.Socket.Types Methods (==) :: SocketStatus -> SocketStatus -> Bool Source # (/=) :: SocketStatus -> SocketStatus -> Bool Source #
Show SocketStatus Source # |
Instance details Defined in Network.Socket.Types Methods showsPrec :: Int -> SocketStatus -> ShowS Source # show :: SocketStatus -> String Source # showList :: [SocketStatus] -> ShowS Source #

isConnected :: Socket -> IO Bool Source #

Deprecated: SocketStatus will be removed

Determines whether `close` has been used on the `Socket`. This does not indicate any status about the socket beyond this. If the socket has been closed remotely, this function can still return `True`.

isBound :: Socket -> IO Bool Source #

Deprecated: SocketStatus will be removed

isListening :: Socket -> IO Bool Source #

Deprecated: SocketStatus will be removed

isReadable :: Socket -> IO Bool Source #

Deprecated: SocketStatus will be removed

isWritable :: Socket -> IO Bool Source #

Deprecated: SocketStatus will be removed

sIsConnected :: Socket -> IO Bool Source #

Deprecated: SocketStatus will be removed

sIsBound :: Socket -> IO Bool Source #

Deprecated: SocketStatus will be removed

sIsListening :: Socket -> IO Bool Source #

Deprecated: SocketStatus will be removed

sIsReadable :: Socket -> IO Bool Source #

Deprecated: SocketStatus will be removed

sIsWritable :: Socket -> IO Bool Source #

Deprecated: SocketStatus will be removed

## Deprecated special constants

aNY_PORT :: PortNumber Source #

Deprecated: Use defaultPort instead

iNADDR_ANY :: HostAddress Source #

Deprecated: Use getAddrInfo instead

The IPv4 wild card address.

iN6ADDR_ANY :: HostAddress6 Source #

Deprecated: Use getAddrInfo instead

The IPv6 wild card address.

sOMAXCONN :: Int Source #

Deprecated: Use maxListenQueue instead

sOL_SOCKET :: Int Source #

Deprecated: This is not necessary anymore

sCM_RIGHTS :: Int Source #

Deprecated: This is not necessary anymore

## Decrecated internal functions

packFamily :: Family -> CInt Source #

unpackFamily :: CInt -> Family Source #

packSocketType :: SocketType -> CInt Source #

Deprecated: packSocketType will not be available in version 3.0.0.0 or later.

## Decrecated UNIX-domain functions

getPeerCred :: Socket -> IO (CUInt, CUInt, CUInt) Source #

Deprecated: Use getPeerCredential instead

Returns the processID, userID and groupID of the socket's peer.

Only available on platforms that support SO_PEERCRED or GETPEEREID(3) on domain sockets. GETPEEREID(3) returns userID and groupID. processID is always 0.

# Orphan instances

Show SockAddr Source # |
Instance details Methods showsPrec :: Int -> SockAddr -> ShowS Source # show :: SockAddr -> String Source # showList :: [SockAddr] -> ShowS Source #