#pragma warning disable IDE1006 // Naming Styles
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Vanara.Extensions;
using Vanara.InteropServices;
namespace Vanara.PInvoke
{
/// Functions, structures and constants from ws2_32.h.
public static partial class Ws2_32
{
/// A flag that describes what types of operation will no longer be allowed.
[PInvokeData("winsock.h", MSDNShortId = "6998f0c6-adc9-481f-b9fb-75f9c9f5caaf")]
public enum SD
{
/// Shutdown receive operations.
SD_RECEIVE = 0,
/// Shutdown send operations.
SD_SEND = 1,
/// Shutdown both send and receive operations.
SD_BOTH = 2,
}
/// The accept function permits an incoming connection attempt on a socket.
///
/// A descriptor that identifies a socket that has been placed in a listening state with the listen function. The connection is
/// actually made with the socket that is returned by accept.
///
///
/// An optional pointer to a buffer that receives the address of the connecting entity, as known to the communications layer. The
/// exact format of the addr parameter is determined by the address family that was established when the socket from the sockaddr
/// structure was created.
///
/// An optional pointer to an integer that contains the length of structure pointed to by the addr parameter.
///
///
/// If no error occurs, accept returns a value of type SOCKET that is a descriptor for the new socket. This returned
/// value is a handle for the socket on which the actual connection is made.
///
/// Otherwise, a value of INVALID_SOCKET is returned, and a specific error code can be retrieved by calling WSAGetLastError.
///
/// The integer referred to by addrlen initially contains the amount of space pointed to by addr. On return it will contain the
/// actual length in bytes of the address returned.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAECONNRESET
/// An incoming connection was indicated, but was subsequently terminated by the remote peer prior to accepting the call.
///
/// -
/// WSAEFAULT
/// The addrlen parameter is too small or addr is not a valid part of the user address space.
///
/// -
/// WSAEINTR
/// A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.
///
/// -
/// WSAEINVAL
/// The listen function was not invoked prior to accept.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEMFILE
/// The queue is nonempty upon entry to accept and there are no descriptors available.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAENOBUFS
/// No buffer space is available.
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
/// -
/// WSAEOPNOTSUPP
/// The referenced socket is not a type that supports connection-oriented service.
///
/// -
/// WSAEWOULDBLOCK
/// The socket is marked as nonblocking and no connections are present to be accepted.
///
///
///
///
///
/// The accept function extracts the first connection on the queue of pending connections on socket s. It then creates and
/// returns a handle to the new socket. The newly created socket is the socket that will handle the actual connection; it has the
/// same properties as socket s, including the asynchronous events registered with the WSAAsyncSelect or WSAEventSelect functions.
///
///
/// The accept function can block the caller until a connection is present if no pending connections are present on the
/// queue, and the socket is marked as blocking. If the socket is marked as nonblocking and no pending connections are present on
/// the queue, accept returns an error as described in the following. After the successful completion of accept
/// returns a new socket handle, the accepted socket cannot be used to accept more connections. The original socket remains open and
/// listens for new connection requests.
///
///
/// The parameter addr is a result parameter that is filled in with the address of the connecting entity, as known to the
/// communications layer. The exact format of the addr parameter is determined by the address family in which the communication is
/// occurring. The addrlen is a value-result parameter; it should initially contain the amount of space pointed to by addr; on
/// return it will contain the actual length (in bytes) of the address returned.
///
///
/// The accept function is used with connection-oriented socket types such as SOCK_STREAM. If addr and/or addrlen are equal
/// to NULL, then no information about the remote address of the accepted socket is returned.
///
///
/// Note When issuing a blocking Winsock call such as accept, Winsock may need to wait for a network event before the
/// call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure
/// call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing
/// blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Example Code
/// The following example demonstrates the use of the accept function.
/// For another example that uses the accept function, see Getting Started With Winsock.
/// Notes for ATM
///
/// The following are important issues associated with connection setup, and must be considered when using Asynchronous Transfer
/// Mode (ATM) with Windows Sockets 2:
///
///
/// -
///
/// The accept and WSAAccept functions do not necessarily set the remote address and address length parameters. Therefore,
/// when using ATM, the caller should use the WSAAccept function and place ATM_CALLING_PARTY_NUMBER_IE in the
/// ProviderSpecific member of the QoS structure, which itself is included in the lpSQOS parameter of the callback function
/// used in accordance with WSAAccept.
///
///
/// -
///
/// When using the accept function, realize that the function may return before connection establishment has traversed the
/// entire distance between sender and receiver. This is because the accept function returns as soon as it receives a CONNECT
/// ACK message; in ATM, a CONNECT ACK message is returned by the next switch in the path as soon as a CONNECT message is processed
/// (rather than the CONNECT ACK being sent by the end node to which the connection is ultimately established). As such,
/// applications should realize that if data is sent immediately following receipt of a CONNECT ACK message, data loss is possible,
/// since the connection may not have been established all the way between sender and receiver.
///
///
///
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-accept SOCKET WSAAPI accept( SOCKET s, sockaddr *addr,
// int *addrlen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock2.h", MSDNShortId = "72246263-4806-4ab2-9b26-89a1782a954b")]
public static extern SOCKET accept(SOCKET s, SOCKADDR addr, ref int addrlen);
/// The accept function permits an incoming connection attempt on a socket.
///
/// A descriptor that identifies a socket that has been placed in a listening state with the listen function. The connection is
/// actually made with the socket that is returned by accept.
///
///
/// An optional pointer to a buffer that receives the address of the connecting entity, as known to the communications layer. The
/// exact format of the addr parameter is determined by the address family that was established when the socket from the sockaddr
/// structure was created.
///
/// An optional pointer to an integer that contains the length of structure pointed to by the addr parameter.
///
///
/// If no error occurs, accept returns a value of type SOCKET that is a descriptor for the new socket. This returned
/// value is a handle for the socket on which the actual connection is made.
///
/// Otherwise, a value of INVALID_SOCKET is returned, and a specific error code can be retrieved by calling WSAGetLastError.
///
/// The integer referred to by addrlen initially contains the amount of space pointed to by addr. On return it will contain the
/// actual length in bytes of the address returned.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAECONNRESET
/// An incoming connection was indicated, but was subsequently terminated by the remote peer prior to accepting the call.
///
/// -
/// WSAEFAULT
/// The addrlen parameter is too small or addr is not a valid part of the user address space.
///
/// -
/// WSAEINTR
/// A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.
///
/// -
/// WSAEINVAL
/// The listen function was not invoked prior to accept.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEMFILE
/// The queue is nonempty upon entry to accept and there are no descriptors available.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAENOBUFS
/// No buffer space is available.
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
/// -
/// WSAEOPNOTSUPP
/// The referenced socket is not a type that supports connection-oriented service.
///
/// -
/// WSAEWOULDBLOCK
/// The socket is marked as nonblocking and no connections are present to be accepted.
///
///
///
///
///
/// The accept function extracts the first connection on the queue of pending connections on socket s. It then creates and
/// returns a handle to the new socket. The newly created socket is the socket that will handle the actual connection; it has the
/// same properties as socket s, including the asynchronous events registered with the WSAAsyncSelect or WSAEventSelect functions.
///
///
/// The accept function can block the caller until a connection is present if no pending connections are present on the
/// queue, and the socket is marked as blocking. If the socket is marked as nonblocking and no pending connections are present on
/// the queue, accept returns an error as described in the following. After the successful completion of accept
/// returns a new socket handle, the accepted socket cannot be used to accept more connections. The original socket remains open and
/// listens for new connection requests.
///
///
/// The parameter addr is a result parameter that is filled in with the address of the connecting entity, as known to the
/// communications layer. The exact format of the addr parameter is determined by the address family in which the communication is
/// occurring. The addrlen is a value-result parameter; it should initially contain the amount of space pointed to by addr; on
/// return it will contain the actual length (in bytes) of the address returned.
///
///
/// The accept function is used with connection-oriented socket types such as SOCK_STREAM. If addr and/or addrlen are equal
/// to NULL, then no information about the remote address of the accepted socket is returned.
///
///
/// Note When issuing a blocking Winsock call such as accept, Winsock may need to wait for a network event before the
/// call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure
/// call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing
/// blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Example Code
/// The following example demonstrates the use of the accept function.
/// For another example that uses the accept function, see Getting Started With Winsock.
/// Notes for ATM
///
/// The following are important issues associated with connection setup, and must be considered when using Asynchronous Transfer
/// Mode (ATM) with Windows Sockets 2:
///
///
/// -
///
/// The accept and WSAAccept functions do not necessarily set the remote address and address length parameters. Therefore,
/// when using ATM, the caller should use the WSAAccept function and place ATM_CALLING_PARTY_NUMBER_IE in the
/// ProviderSpecific member of the QoS structure, which itself is included in the lpSQOS parameter of the callback function
/// used in accordance with WSAAccept.
///
///
/// -
///
/// When using the accept function, realize that the function may return before connection establishment has traversed the
/// entire distance between sender and receiver. This is because the accept function returns as soon as it receives a CONNECT
/// ACK message; in ATM, a CONNECT ACK message is returned by the next switch in the path as soon as a CONNECT message is processed
/// (rather than the CONNECT ACK being sent by the end node to which the connection is ultimately established). As such,
/// applications should realize that if data is sent immediately following receipt of a CONNECT ACK message, data loss is possible,
/// since the connection may not have been established all the way between sender and receiver.
///
///
///
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-accept SOCKET WSAAPI accept( SOCKET s, sockaddr *addr,
// int *addrlen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock2.h", MSDNShortId = "72246263-4806-4ab2-9b26-89a1782a954b")]
public static extern SOCKET accept(SOCKET s, [Optional] IntPtr addr, [Optional] IntPtr addrlen);
/// The bind function associates a local address with a socket.
/// A descriptor identifying an unbound socket.
/// TBD
/// The length, in bytes, of the value pointed to by the name parameter.
///
///
/// If no error occurs, bind returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code can be retrieved by
/// calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
///
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEACCES
///
/// An attempt was made to access a socket in a way forbidden by its access permissions. This error is returned if nn attempt to
/// bind a datagram socket to the broadcast address failed because the setsockopt option SO_BROADCAST is not enabled.
///
///
/// -
/// WSAEADDRINUSE
///
/// Only one usage of each socket address (protocol/network address/port) is normally permitted. This error is returned if a process
/// on the computer is already bound to the same fully qualified address and the socket has not been marked to allow address reuse
/// with SO_REUSEADDR. For example, the IP address and port specified in the name parameter are already bound to another socket
/// being used by another application. For more information, see the SO_REUSEADDR socket option in the SOL_SOCKET Socket Options
/// reference, Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE, and SO_EXCLUSIVEADDRUSE.
///
///
/// -
/// WSAEADDRNOTAVAIL
///
/// The requested address is not valid in its context. This error is returned if the specified address pointed to by the name
/// parameter is not a valid local IP address on this computer.
///
///
/// -
/// WSAEFAULT
///
/// The system detected an invalid pointer address in attempting to use a pointer argument in a call. This error is returned if the
/// name parameter is NULL, the name or namelen parameter is not a valid part of the user address space, the namelen parameter is
/// too small, the name parameter contains an incorrect address format for the associated address family, or the first two bytes of
/// the memory block specified by name do not match the address family associated with the socket descriptor s.
///
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEINVAL
/// An invalid argument was supplied. This error is returned of the socket s is already bound to an address.
///
/// -
/// WSAENOBUFS
///
/// An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.
/// This error is returned of not enough buffers are available or there are too many connections.
///
///
/// -
/// WSAENOTSOCK
///
/// An operation was attempted on something that is not a socket. This error is returned if the descriptor in the s parameter is not
/// a socket.
///
///
///
///
///
///
/// The bind function is required on an unconnected socket before subsequent calls to the listen function. It is normally
/// used to bind to either connection-oriented (stream) or connectionless (datagram) sockets. The bind function may also be
/// used to bind to a raw socket (the socket was created by calling the socketfunction with the type parameter set to SOCK_RAW). The
/// bind function may also be used on an unconnected socket before subsequent calls to the connect, ConnectEx, WSAConnect,
/// WSAConnectByList, or WSAConnectByName functions before send operations.
///
///
/// When a socket is created with a call to the socket function, it exists in a namespace (address family), but it has no name
/// assigned to it. Use the bind function to establish the local association of the socket by assigning a local name to an
/// unnamed socket.
///
/// A name consists of three parts when using the Internet address family:
///
/// -
/// The address family.
///
/// -
/// A host address.
///
/// -
/// A port number that identifies the application.
///
///
///
/// In Windows Sockets 2, the name parameter is not strictly interpreted as a pointer to a sockaddr structure. It is cast this way
/// for Windows Sockets 1.1 compatibility. Service providers are free to regard it as a pointer to a block of memory of size
/// namelen. The first 2 bytes in this block (corresponding to the sa_family member of the sockaddr structure, the
/// sin_family member of the sockaddr_in structure, or the sin6_family member of the sockaddr_in6
/// structure) must contain the address family that was used to create the socket. Otherwise, an error WSAEFAULT occurs.
///
///
/// If an application does not care what local address is assigned, specify the constant value INADDR_ANY for an IPv4 local
/// address or the constant value in6addr_any for an IPv6 local address in the sa_data member of the name parameter.
/// This allows the underlying service provider to use any appropriate network address, potentially simplifying application
/// programming in the presence of multihomed hosts (that is, hosts that have more than one network interface and address).
///
///
/// For TCP/IP, if the port is specified as zero, the service provider assigns a unique port to the application from the dynamic
/// client port range. On Windows Vista and later, the dynamic client port range is a value between 49152 and 65535. This is a
/// change from Windows Server 2003 and earlier where the dynamic client port range was a value between 1025 and 5000. The maximum
/// value for the client dynamic port range can be changed by setting a value under the following registry key:
///
/// HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
///
/// The MaxUserPort registry value sets the value to use for the maximum value of the dynamic client port range. You must
/// restart the computer for this setting to take effect.
///
///
/// On Windows Vista and later, the dynamic client port range can be viewed and changed using netsh commands. The dynamic
/// client port range can be set differently for UDP and TCP and also for IPv4 and IPv6. For more information, see KB 929851.
///
///
/// The application can use getsockname after calling bind to learn the address and the port that has been assigned to the
/// socket. If the Internet address is equal to INADDR_ANY or in6addr_any, getsockname cannot necessarily
/// supply the address until the socket is connected, since several addresses can be valid if the host is multihomed. Binding to a
/// specific port number other than port 0 is discouraged for client applications, since there is a danger of conflicting with
/// another socket already using that port number on the local computer.
///
///
/// For multicast operations, the preferred method is to call the bind function to associate a socket with a local IP address
/// and then join the multicast group. Although this order of operations is not mandatory, it is strongly recommended. So a
/// multicast application would first select an IPv4 or IPv6 address on the local computer, the wildcard IPv4 address (
/// INADDR_ANY), or the wildcard IPv6 address ( in6addr_any). The the multicast application would then call the
/// bind function with this address in the in the sa_data member of the name parameter to associate the local IP
/// address with the socket. If a wildcard address was specified, then Windows will select the local IP address to use. After the
/// bind function completes, an application would then join the multicast group of interest. For more information on how to
/// join a multicast group, see the section on Multicast Programming. This socket can then be used to receive multicast packets from
/// the multicast group using the recv, recvfrom, WSARecv, WSARecvEx, WSARecvFrom, or WSARecvMsg functions.
///
///
/// The bind function is not normally required for send operations to a multicast group. The sendto,WSASendMsg, and WSASendTo
/// functions implicitly bind the socket to the wildcard address if the socket is not already bound. The bind function is
/// required before the use of the send or WSASend functions which do not perform an implicit bind and are allowed only on connected
/// sockets, which means the socket must have already been bound for it to be connected. The bind function might be used
/// before send operations using the sendto, WSASendMsg, or WSASendTo functions if an application wanted to
/// select a specific local IP address on a local computer with multiple network interfaces and local IP addresses. Otherwise an
/// implicit bind to the wildcard address using the sendto, WSASendMsg , or WSASendTo functions might result in
/// a different local IP address being used for send operations.
///
///
/// Note When issuing a blocking Winsock call such as bind, Winsock may need to wait for a network event before the
/// call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure
/// call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing
/// blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Notes for IrDA Sockets
///
/// -
/// The Af_irda.h header file must be explicitly included.
///
/// -
///
/// Local names are not exposed in IrDA. IrDA client sockets therefore, must never call the bind function before the connect
/// function. If the IrDA socket was previously bound to a service name using bind, the connect function will fail
/// with SOCKET_ERROR.
///
///
/// -
///
/// If the service name is of the form "LSAP-SELxxx," where xxx is a decimal integer in the range 1-127, the address indicates a
/// specific LSAP-SEL xxx rather than a service name. Service names such as these allow server applications to accept incoming
/// connections directed to a specific LSAP-SEL, without first performing an ISA service name query to get the associated LSAP-SEL.
/// One example of this service name type is a non-Windows device that does not support IAS.
///
///
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
/// Examples
///
/// The following example demonstrates the use of the bind function. For another example that uses the bind function,
/// see Getting Started With Winsock.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-bind int bind( SOCKET s, const sockaddr *addr, int
// namelen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "3a651daa-7404-4ef7-8cff-0d3dff41a8e8")]
public static extern int bind(SOCKET s, [In] SOCKADDR addr, int namelen);
/// The closesocket function closes an existing socket.
/// A descriptor identifying the socket to close.
///
///
/// If no error occurs, closesocket returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error
/// code can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEINTR
/// The (blocking) Windows Socket 1.1 call was canceled through WSACancelBlockingCall.
///
/// -
/// WSAEWOULDBLOCK
///
/// The socket is marked as nonblocking, but the l_onoff member of the linger structure is set to nonzero and the l_linger member of
/// the linger structure is set to a nonzero timeout value.
///
///
///
///
///
///
/// The closesocket function closes a socket. Use it to release the socket descriptor passed in the s parameter. Note that
/// the socket descriptor passed in the s parameter may immediately be reused by the system as soon as closesocket function
/// is issued. As a result, it is not reliable to expect further references to the socket descriptor passed in the s parameter to
/// fail with the error WSAENOTSOCK. A Winsock client must never issue closesocket on s concurrently with another Winsock
/// function call.
///
///
/// Any pending overlapped send and receive operations ( WSASend/ WSASendTo/ WSARecv/ WSARecvFrom with an overlapped socket) issued
/// by any thread in this process are also canceled. Any event, completion routine, or completion port action specified for these
/// overlapped operations is performed. The pending overlapped operations fail with the error status WSA_OPERATION_ABORTED.
///
///
/// An application should not assume that any outstanding I/O operations on a socket will all be guaranteed to completed when
/// closesocket returns. The closesocket function will initiate cancellation on the outstanding I/O operations, but
/// that does not mean that an application will receive I/O completion for these I/O operations by the time the closesocket
/// function returns. Thus, an application should not cleanup any resources (WSAOVERLAPPED structures, for example) referenced by
/// the outstanding I/O requests until the I/O requests are indeed completed.
///
///
/// An application should always have a matching call to closesocket for each successful call to socket to return any socket
/// resources to the system.
///
///
/// The linger structure maintains information about a specific socket that specifies how that socket should behave when data is
/// queued to be sent and the closesocket function is called on the socket.
///
///
/// The l_onoff member of the linger structure determines whether a socket should remain open for a specified amount
/// of time after a closesocket function call to enable queued data to be sent. This member can be modified in two ways:
///
///
/// -
///
/// Call the setsockopt function with the optname parameter set to SO_DONTLINGER. The optval parameter determines how the
/// l_onoff member is modified.
///
///
/// -
///
/// Call the setsockopt function with the optname parameter set to SO_LINGER. The optval parameter specifies how both the
/// l_onoff and l_linger members are modified.
///
///
///
///
/// The l_linger member of the linger structure determines the amount of time, in seconds, a socket should remain
/// open. This member is only applicable if the l_onoff member of the linger structure is nonzero.
///
///
/// The default parameters for a socket are the l_onoff member of the linger structure is zero, indicating that the
/// socket should not remain open. The default value for the l_linger member of the linger structure is zero, but this
/// value is ignored when the l_onoff member is set to zero.
///
///
/// To enable a socket to remain open, an application should set the l_onoff member to a nonzero value and set the
/// l_linger member to the desired timeout in seconds. To disable a socket from remaining open, an application only needs to
/// set the l_onoff member of the linger structure to zero.
///
///
/// If an application calls the setsockopt function with the optname parameter set to SO_DONTLINGER to set the l_onoff
/// member to a nonzero value, the value for the l_linger member is not specified. In this case, the timeout used is
/// implementation dependent. If a previous timeout has been established for a socket (by previously calling the setsockopt
/// function with the optname parameter set to SO_LINGER), this timeout value should be reinstated by the service provider.
///
///
/// The semantics of the closesocket function are affected by the socket options that set members of linger structure.
///
///
///
/// l_onoff
/// l_linger
/// Type of close
/// Wait for close?
///
/// -
/// zero
/// Do not care
/// Graceful close
/// No
///
/// -
/// nonzero
/// zero
/// Hard
/// No
///
/// -
/// nonzero
/// nonzero
///
/// Graceful if all data is sent within timeout value specified in the l_linger member. Hard if all data could not be sent within
/// timeout value specified in the l_linger member.
///
/// Yes
///
///
///
/// If the l_onoff member of the LINGER structure is zero on a stream socket, the closesocket call will return
/// immediately and does not receive WSAEWOULDBLOCK whether the socket is blocking or nonblocking. However, any data queued for
/// transmission will be sent, if possible, before the underlying socket is closed. This is also called a graceful disconnect or
/// close. In this case, the Windows Sockets provider cannot release the socket and other resources for an arbitrary period, thus
/// affecting applications that expect to use all available sockets. This is the default behavior for a socket.
///
///
/// If the l_onoff member of the linger structure is nonzero and l_linger member is zero, closesocket is not
/// blocked even if queued data has not yet been sent or acknowledged. This is called a hard or abortive close, because the socket's
/// virtual circuit is reset immediately, and any unsent data is lost. On Windows, any recv call on the remote side of the
/// circuit will fail with WSAECONNRESET.
///
///
/// If the l_onoff member of the linger structure is set to nonzero and l_linger member is set to a nonzero timeout on
/// a blocking socket, the closesocket call blocks until the remaining data has been sent or until the timeout expires. This
/// is called a graceful disconnect or close if all of the data is sent within timeout value specified in the l_linger
/// member. If the timeout expires before all data has been sent, the Windows Sockets implementation terminates the connection
/// before closesocket returns and this is called a hard or abortive close.
///
///
/// Setting the l_onoff member of the linger structure to nonzero and the l_linger member with a nonzero timeout
/// interval on a nonblocking socket is not recommended. In this case, the call to closesocket will fail with an error of
/// WSAEWOULDBLOCK if the close operation cannot be completed immediately. If closesocket fails with WSAEWOULDBLOCK the
/// socket handle is still valid, and a disconnect is not initiated. The application must call closesocket again to close the socket.
///
///
/// If the l_onoff member of the linger structure is nonzero and the l_linger member is a nonzero timeout interval on
/// a blocking socket, the result of the closesocket function can't be used to determine whether all data has been sent to
/// the peer. If the data is sent before the timeout specified in the l_linger member expires or if the connection was
/// aborted, the closesocket function won't return an error code (the return value from the closesocket function is zero).
///
///
/// The closesocket call will only block until all data has been delivered to the peer or the timeout expires. If the
/// connection is reset because the timeout expires, then the socket will not go into TIME_WAIT state. If all data is sent within
/// the timeout period, then the socket can go into TIME_WAIT state.
///
///
/// If the l_onoff member of the linger structure is nonzero and the l_linger member is a zero timeout interval on a
/// blocking socket, then a call to closesocket will reset the connection. The socket will not go to the TIME_WAIT state.
///
///
/// The getsockopt function can be called with the optname parameter set to SO_LINGER to retrieve the current value of the
/// linger structure associated with a socket.
///
///
/// Note To assure that all data is sent and received on a connection, an application should call shutdown before calling
/// closesocket (see Graceful shutdown, linger options, and socket closure for more information). Also note, an FD_CLOSE
/// network event is not posted after closesocket is called.
///
/// Here is a summary of closesocket behavior:
///
/// -
///
/// If the l_onoff member of the LINGER structure is zero (the default for a socket), closesocket returns immediately
/// and the connection is gracefully closed in the background.
///
///
/// -
///
/// If the l_onoff member of the linger structure is set to nonzero and the l_linger member is set to zero (no
/// timeout) closesocket returns immediately and the connection is reset or terminated.
///
///
/// -
///
/// If the l_onoff member of the linger structure is set to nonzero and the l_linger member is set to a nonzero
/// timeout:– For a blocking socket, closesocket blocks until all data is sent or the timeout expires.
///
///
///
/// For additional information please see Graceful Shutdown, Linger Options, and Socket Closure for more information.
///
/// Note When issuing a blocking Winsock call such as closesocket, Winsock may need to wait for a network event before
/// the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous
/// procedure call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an
/// ongoing blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Notes for IrDA Sockets
/// Keep the following in mind:
///
/// -
/// The Af_irda.h header file must be explicitly included.
///
/// -
/// The standard linger options are supported.
///
/// -
///
/// Although IrDA does not provide a graceful close, IrDA will defer closing until receive queues are purged. Thus, an application
/// can send data and immediately call the socket function, and be confident that the receiver will copy the data before receiving
/// an FD_CLOSE message.
///
///
///
/// Notes for ATM
///
/// The following are important issues associated with connection teardown when using Asynchronous Transfer Mode (ATM) and Windows
/// Sockets 2:
///
///
/// -
///
/// Using the closesocket or shutdown functions with SD_SEND or SD_BOTH results in a RELEASE signal being sent out on the
/// control channel. Due to ATM's use of separate signal and data channels, it is possible that a RELEASE signal could reach the
/// remote end before the last of the data reaches its destination, resulting in a loss of that data. One possible solutions is
/// programming a sufficient delay between the last data sent and the closesocket or shutdown function calls for an ATM socket.
///
///
/// -
/// Half close is not supported by ATM.
///
/// -
///
/// Both abortive and graceful disconnects result in a RELEASE signal being sent out with the same cause field. In either case,
/// received data at the remote end of the socket is still delivered to the application. See Graceful Shutdown, Linger Options, and
/// Socket Closure for more information.
///
///
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-closesocket int closesocket( IN SOCKET s );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "2f357aa8-389b-4c92-8a9f-289e048cc41c")]
public static extern int closesocket([In] SOCKET s);
/// The connect function establishes a connection to a specified socket.
/// A descriptor identifying an unconnected socket.
/// A pointer to the sockaddr structure to which the connection should be established.
/// The length, in bytes, of the sockaddr structure pointed to by the name parameter.
///
///
/// If no error occurs, connect returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code can be retrieved
/// by calling WSAGetLastError.
///
/// On a blocking socket, the return value indicates success or failure of the connection attempt.
///
/// With a nonblocking socket, the connection attempt cannot be completed immediately. In this case, connect will return
/// SOCKET_ERROR, and WSAGetLastError will return WSAEWOULDBLOCK. In this case, there are three possible scenarios:
///
///
/// -
/// Use the select function to determine the completion of the connection request by checking to see if the socket is writeable.
///
/// -
///
/// If the application is using WSAAsyncSelect to indicate interest in connection events, then the application will receive an
/// FD_CONNECT notification indicating that the connect operation is complete (successfully or not).
///
///
/// -
///
/// If the application is using WSAEventSelect to indicate interest in connection events, then the associated event object will be
/// signaled indicating that the connect operation is complete (successfully or not).
///
///
///
///
/// Until the connection attempt completes on a nonblocking socket, all subsequent calls to connect on the same socket will
/// fail with the error code WSAEALREADY, and WSAEISCONN when the connection completes successfully. Due to ambiguities in version
/// 1.1 of the Windows Sockets specification, error codes returned from connect while a connection is already pending may
/// vary among implementations. As a result, it is not recommended that applications use multiple calls to connect to detect
/// connection completion. If they do, they must be prepared to handle WSAEINVAL and WSAEWOULDBLOCK error values the same way that
/// they handle WSAEALREADY, to assure robust operation.
///
///
/// If the error code returned indicates the connection attempt failed (that is, WSAECONNREFUSED, WSAENETUNREACH, WSAETIMEDOUT) the
/// application can call connect again for the same socket.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEADDRINUSE
///
/// The socket's local address is already in use and the socket was not marked to allow address reuse with SO_REUSEADDR. This error
/// usually occurs when executing bind, but could be delayed until the connect function if the bind was to a wildcard address
/// (INADDR_ANY or in6addr_any) for the local IP address. A specific address needs to be implicitly bound by the connect function.
///
///
/// -
/// WSAEINTR
/// The blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEALREADY
/// A nonblocking connect call is in progress on the specified socket.
///
/// -
/// WSAEADDRNOTAVAIL
/// The remote address is not a valid address (such as INADDR_ANY or in6addr_any) .
///
/// -
/// WSAEAFNOSUPPORT
/// Addresses in the specified family cannot be used with this socket.
///
/// -
/// WSAECONNREFUSED
/// The attempt to connect was forcefully rejected.
///
/// -
/// WSAEFAULT
///
/// The sockaddr structure pointed to by the name contains incorrect address format for the associated address family or the namelen
/// parameter is too small. This error is also returned if the sockaddr structure pointed to by the name parameter with a length
/// specified in the namelen parameter is not in a valid part of the user address space.
///
///
/// -
/// WSAEINVAL
/// The parameter s is a listening socket.
///
/// -
/// WSAEISCONN
/// The socket is already connected (connection-oriented sockets only).
///
/// -
/// WSAENETUNREACH
/// The network cannot be reached from this host at this time.
///
/// -
/// WSAEHOSTUNREACH
/// A socket operation was attempted to an unreachable host.
///
/// -
/// WSAENOBUFS
///
///
/// -
/// WSAENOTSOCK
/// The descriptor specified in the s parameter is not a socket.
///
/// -
/// WSAETIMEDOUT
/// An attempt to connect timed out without establishing a connection.
///
/// -
/// WSAEWOULDBLOCK
/// The socket is marked as nonblocking and the connection cannot be completed immediately.
///
/// -
/// WSAEACCES
/// An attempt to connect a datagram socket to broadcast address failed because setsockopt option SO_BROADCAST is not enabled.
///
///
///
///
///
/// The connect function is used to create a connection to the specified destination. If socket s, is unbound, unique values
/// are assigned to the local association by the system, and the socket is marked as bound.
///
///
/// For connection-oriented sockets (for example, type SOCK_STREAM), an active connection is initiated to the foreign host using
/// name (an address in the namespace of the socket; for a detailed description, see bind and sockaddr).
///
///
/// When the socket call completes successfully, the socket is ready to send and receive data. If the address member of the
/// structure specified by the name parameter is filled with zeros, connect will return the error WSAEADDRNOTAVAIL. Any
/// attempt to reconnect an active connection will fail with the error code WSAEISCONN.
///
///
/// For connection-oriented, nonblocking sockets, it is often not possible to complete the connection immediately. In such a case,
/// this function returns the error WSAEWOULDBLOCK. However, the operation proceeds.
///
///
/// When the success or failure outcome becomes known, it may be reported in one of two ways, depending on how the client registers
/// for notification.
///
///
/// -
///
/// If the client uses the select function, success is reported in the writefds set and failure is reported in the exceptfds set.
///
///
/// -
///
/// If the client uses the functions WSAAsyncSelect or WSAEventSelect, the notification is announced with FD_CONNECT and the error
/// code associated with the FD_CONNECT indicates either success or a specific reason for failure.
///
///
///
///
/// For a connectionless socket (for example, type SOCK_DGRAM), the operation performed by connect is merely to establish a
/// default destination address that can be used on subsequent send/ WSASend and recv/ WSARecv calls. Any datagrams received from an
/// address other than the destination address specified will be discarded. If the address member of the structure specified by name
/// is filled with zeros, the socket will be disconnected. Then, the default remote address will be indeterminate, so send/ WSASend
/// and recv/ WSARecv calls will return the error code WSAENOTCONN. However, sendto/ WSASendTo and recvfrom/ WSARecvFrom can still
/// be used. The default destination can be changed by simply calling connect again, even if the socket is already connected.
/// Any datagrams queued for receipt are discarded if name is different from the previous connect.
///
///
/// For connectionless sockets, name can indicate any valid address, including a broadcast address. However, to connect to a
/// broadcast address, a socket must use setsockopt to enable the SO_BROADCAST option. Otherwise, connect will fail with the
/// error code WSAEACCES.
///
///
/// When a connection between sockets is broken, the socket that was connected should be discarded and new socket should be created.
/// When a problem develops on a connected socket, the application must discard the socket and create the socket again in order to
/// return to a stable point.
///
///
/// Note When issuing a blocking Winsock call such as connect, Winsock may need to wait for a network event before the
/// call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure
/// call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing
/// blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Example Code
/// The following example demonstrates the use of the connect function.
/// For another example that uses the connect function, see Getting Started With Winsock.
/// Notes for IrDA Sockets
///
/// -
/// The Af_irda.h header file must be explicitly included.
///
/// -
/// If an existing IrDA connection is detected at the media-access level, WSAENETDOWN is returned.
///
/// -
/// If active connections to a device with a different address exist, WSAEADDRINUSE is returned.
///
/// -
/// If the socket is already connected or an exclusive/multiplexed mode change failed, WSAEISCONN is returned.
///
/// -
///
/// If the socket was previously bound to a local service name to accept incoming connections using bind, WSAEINVAL is returned.
/// Note that once a socket is bound, it cannot be used for establishing an outbound connection.
///
///
///
///
/// IrDA implements the connect function with addresses of the form sockaddr_irda. Typically, a client application will create a
/// socket with the socket function, scan the immediate vicinity for IrDA devices with the IRLMP_ENUMDEVICES socket option, choose a
/// device from the returned list, form an address, and then call connect. There is no difference between blocking and
/// nonblocking semantics.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-connect int WSAAPI connect( SOCKET s, const sockaddr
// *name, int namelen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock2.h", MSDNShortId = "13468139-dc03-45bd-850c-7ac2dbcb6e60")]
public static extern int connect(SOCKET s, SOCKADDR name, int namelen);
/// The gethostname function retrieves the standard host name for the local computer.
/// A pointer to a buffer that receives the local host name.
/// The length, in bytes, of the buffer pointed to by the name parameter.
///
///
/// If no error occurs, gethostname returns zero. Otherwise, it returns SOCKET_ERROR and a specific error code can be
/// retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSAEFAULT
///
/// The name parameter is a NULL pointer or is not a valid part of the user address space. This error is also returned if the buffer
/// size specified by namelen parameter is too small to hold the complete host name.
///
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
///
///
///
///
/// The gethostname function returns the name of the local host into the buffer specified by the name parameter. The host
/// name is returned as a null-terminated string. The form of the host name is dependent on the Windows Sockets provider—it
/// can be a simple host name, or it can be a fully qualified domain name. However, it is guaranteed that the name returned will be
/// successfully parsed by gethostbyname and WSAAsyncGetHostByName.
///
/// The maximum length of the name returned in the buffer pointed to by the name parameter is dependent on the namespace provider.
///
/// If the gethostname function is used on a cluster resource on Windows Server 2008, Windows Server 2003, or Windows 2000
/// Server and the CLUSTER_NETWORK_NAME environment variable is defined, then the value in this environment variable overrides the
/// actual hostname and is returned. On a cluster resource, the CLUSTER_NETWORK_NAME environment variable contains the name of the cluster.
///
///
/// The gethostname function queries namespace providers to determine the local host name using the SVCID_HOSTNAME GUID
/// defined in the Svgguid.h header file. If no namespace provider responds, then the gethostname function returns the
/// NetBIOS name of the local computer.
///
///
/// The maximum length, in bytes, of the string returned in the buffer pointed to by the name parameter is dependent on the
/// namespace provider, but this string must be 256 bytes or less. So if a buffer of 256 bytes is passed in the name parameter and
/// the namelen parameter is set to 256, the buffer size will always be adequate.
///
///
/// Note If no local host name has been configured, gethostname must succeed and return a token host name that
/// gethostbyname or WSAAsyncGetHostByName can resolve.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-gethostname int gethostname( char *name, int namelen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Ansi)]
[PInvokeData("winsock.h", MSDNShortId = "8fa40b60-0e93-493b-aee1-cea6cf595707")]
public static extern int gethostname(StringBuilder name, int namelen);
/// The GetHostNameW function retrieves the standard host name for the local computer as a Unicode string.
/// A pointer to a buffer that receives the local host name as a null-terminated Unicode string.
/// The length, in wide characters, of the buffer pointed to by the name parameter.
///
///
/// If no error occurs, GetHostNameW returns zero. Otherwise, it returns SOCKET_ERROR and a specific error code can be
/// retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSAEFAULT
///
/// The name parameter is a NULL pointer or is not a valid part of the user address space. This error is also returned if the buffer
/// size specified by namelen parameter is too small to hold the complete host name.
///
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
///
///
///
///
/// The GetHostNameW function returns the name of the local host into the buffer specified by the name parameter in Unicode
/// (UTF-16). The host name is returned as a null-terminated Unicode string. The form of the host name is dependent on the
/// Windows Sockets provider—it can be a simple host name, or it can be a fully qualified domain name. However, it is guaranteed
/// that the name returned will be successfully parsed by GetAddrInfoW.
///
///
/// With the growth of the Internet, there is a growing need to identify Internet host names for other languages not represented by
/// the ASCII character set. Identifiers which facilitate this need and allow non-ASCII characters (Unicode) to be represented as
/// special ASCII character strings (Punycode) are known as Internationalized Domain Names (IDNs). A mechanism called
/// Internationalizing Domain Names in Applications (IDNA) is used to handle IDNs in a standard fashion. The GetHostNameW
/// function does not convert the local hostname between Punycode and Unicode. The GetAddrInfoW function provides support for
/// Internationalized Domain Name (IDN) parsing and performs Punycode/IDN encoding and conversion.
///
///
/// If the GetHostNameW function is used on a cluster resource on Windows Server 2012 and the CLUSTER_NETWORK_NAME
/// environment variable is defined, then the value in this environment variable overrides the actual hostname and is returned. On a
/// cluster resource, the CLUSTER_NETWORK_NAME environment variable contains the name of the cluster.
///
///
/// The GetHostNameW function queries namespace providers to determine the local host name using the SVCID_HOSTNAME GUID
/// defined in the Svgguid.h header file. If no namespace provider responds, then the GetHostNameW function returns the
/// NetBIOS name of the local computer in Unicode.
///
///
/// The maximum length, in wide characters, of the string returned in the buffer pointed to by the name parameter is dependent on
/// the namespace provider, but this string must be 256 wide characters or less. So if a buffer of 256 wide characters is passed in
/// the name parameter and the namelen parameter is set to 256, the buffer size will always be adequate.
///
///
/// Note If no local host name has been configured, GetHostNameW must succeed and return a token host name that
/// GetAddrInfoW can resolve.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-gethostnamew int WSAAPI GetHostNameW( PWSTR name, int
// namelen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("winsock2.h", MSDNShortId = "787EB209-5944-4F0A-8550-FE1115C2298A")]
public static extern int GetHostNameW(StringBuilder name, int namelen);
/// The getpeername function retrieves the address of the peer to which a socket is connected.
/// A descriptor identifying a connected socket.
/// The SOCKADDR structure that receives the address of the peer.
/// A pointer to the size, in bytes, of the name parameter.
///
///
/// If no error occurs, getpeername returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code
/// can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEFAULT
/// The name or the namelen parameter is not in a valid part of the user address space, or the namelen parameter is too small.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAENOTCONN
/// The socket is not connected.
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
///
///
///
///
/// The getpeername function retrieves the address of the peer connected to the socket s and stores the address in the
/// SOCKADDR structure identified by the name parameter. This function works with any address family and it simply returns the
/// address to which the socket is connected. The getpeername function can be used only on a connected socket.
///
///
/// For datagram sockets, only the address of a peer specified in a previous connect call will be returned. Any address specified by
/// a previous sendto call will not be returned by getpeername.
///
///
/// On call, the namelen parameter contains the size, in bytes, of the name buffer. On return, the namelen parameter contains the
/// actual size, in bytes, of the name parameter returned.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-getpeername int getpeername( SOCKET s, sockaddr *name, int
// *namelen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "df2679a5-cdd9-468b-823a-f98044189f65")]
public static extern int getpeername(SOCKET s, SOCKADDR name, ref int namelen);
/// The getprotobyname function retrieves the protocol information corresponding to a protocol name.
/// Pointer to a null-terminated protocol name.
///
///
/// If no error occurs, getprotobyname returns a pointer to the protoent. Otherwise, it returns a null pointer and a specific
/// error number can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAHOST_NOT_FOUND
/// Authoritative answer protocol not found.
///
/// -
/// WSATRY_AGAIN
/// A nonauthoritative protocol not found, or server failure.
///
/// -
/// WSANO_RECOVERY
/// Nonrecoverable errors, the protocols database is not accessible.
///
/// -
/// WSANO_DATA
/// Valid name, no data record of requested type.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEFAULT
/// The name parameter is not a valid part of the user address space.
///
/// -
/// WSAEINTR
/// A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.
///
///
///
///
///
/// The getprotobyname function returns a pointer to the protoent structure containing the name(s) and protocol number that
/// correspond to the protocol specified in the name parameter. All strings are null-terminated. The protoent structure is
/// allocated by the Windows Sockets library. An application must never attempt to modify this structure or to free any of its
/// components. Furthermore, like hostent, only one copy of this structure is allocated per thread, so the application should copy
/// any information that it needs before issuing any other Windows Sockets function calls.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-getprotobyname protoent * getprotobyname( const char *name );
[DllImport(Lib.Ws2_32, SetLastError = true, EntryPoint = "getprotobyname", CharSet = CharSet.Ansi)]
[PInvokeData("winsock.h", MSDNShortId = "00669525-d477-4607-beaa-61ef5a8dbd4f")]
public static extern unsafe PROTOENT* getprotobyname_unsafe(string name);
/// The getprotobyname function retrieves the protocol information corresponding to a protocol name.
/// Pointer to a null-terminated protocol name.
///
///
/// If no error occurs, getprotobyname returns a pointer to the protoent. Otherwise, it returns a null pointer and a specific
/// error number can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAHOST_NOT_FOUND
/// Authoritative answer protocol not found.
///
/// -
/// WSATRY_AGAIN
/// A nonauthoritative protocol not found, or server failure.
///
/// -
/// WSANO_RECOVERY
/// Nonrecoverable errors, the protocols database is not accessible.
///
/// -
/// WSANO_DATA
/// Valid name, no data record of requested type.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEFAULT
/// The name parameter is not a valid part of the user address space.
///
/// -
/// WSAEINTR
/// A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.
///
///
///
///
///
/// The getprotobyname function returns a pointer to the protoent structure containing the name(s) and protocol number that
/// correspond to the protocol specified in the name parameter. All strings are null-terminated. The protoent structure is
/// allocated by the Windows Sockets library. An application must never attempt to modify this structure or to free any of its
/// components. Furthermore, like hostent, only one copy of this structure is allocated per thread, so the application should copy
/// any information that it needs before issuing any other Windows Sockets function calls.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-getprotobyname protoent * getprotobyname( const char *name );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Ansi)]
[PInvokeData("winsock.h", MSDNShortId = "00669525-d477-4607-beaa-61ef5a8dbd4f")]
public static extern IntPtr getprotobyname(string name);
/// The getprotobynumber function retrieves protocol information corresponding to a protocol number.
///
///
///
/// If no error occurs, getprotobynumber returns a pointer to the protoent structure. Otherwise, it returns a null pointer
/// and a specific error number can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAHOST_NOT_FOUND
/// Authoritative answer protocol not found.
///
/// -
/// WSATRY_AGAIN
/// A nonauthoritative Protocol not found, or server failure.
///
/// -
/// WSANO_RECOVERY
/// Nonrecoverable errors, the protocols database is not accessible.
///
/// -
/// WSANO_DATA
/// Valid name, no data record of requested type.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEINTR
/// A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.
///
///
///
///
///
/// This getprotobynumber function returns a pointer to the protoent structure as previously described in getprotobyname. The
/// contents of the structure correspond to the given protocol number.
///
///
/// The pointer that is returned points to the structure allocated by Windows Sockets. The application must never attempt to modify
/// this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, so the
/// application should copy any information that it needs before issuing any other Windows Sockets function calls.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-getprotobynumber protoent *WSAAPI getprotobynumber( int
// number );
[DllImport(Lib.Ws2_32, SetLastError = true, EntryPoint = "getprotobynumber")]
[PInvokeData("winsock2.h", MSDNShortId = "f1f55ab7-01ca-4ed7-b8f9-e7ddbaa95855")]
public static extern unsafe PROTOENT* getprotobynumber_unsafe(int number);
/// The getprotobynumber function retrieves protocol information corresponding to a protocol number.
///
///
///
/// If no error occurs, getprotobynumber returns a pointer to the protoent structure. Otherwise, it returns a null pointer
/// and a specific error number can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAHOST_NOT_FOUND
/// Authoritative answer protocol not found.
///
/// -
/// WSATRY_AGAIN
/// A nonauthoritative Protocol not found, or server failure.
///
/// -
/// WSANO_RECOVERY
/// Nonrecoverable errors, the protocols database is not accessible.
///
/// -
/// WSANO_DATA
/// Valid name, no data record of requested type.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEINTR
/// A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.
///
///
///
///
///
/// This getprotobynumber function returns a pointer to the protoent structure as previously described in getprotobyname. The
/// contents of the structure correspond to the given protocol number.
///
///
/// The pointer that is returned points to the structure allocated by Windows Sockets. The application must never attempt to modify
/// this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, so the
/// application should copy any information that it needs before issuing any other Windows Sockets function calls.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-getprotobynumber protoent *WSAAPI getprotobynumber( int
// number );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock2.h", MSDNShortId = "f1f55ab7-01ca-4ed7-b8f9-e7ddbaa95855")]
public static extern IntPtr getprotobynumber(int number);
/// The getservbyname function retrieves service information corresponding to a service name and protocol.
/// A pointer to a null-terminated service name.
///
/// A pointer to a null-terminated protocol name. If this pointer is NULL, the getservbyname function returns
/// the first service entry where name matches the s_name member of the servent structure or the s_aliases member of
/// the servent structure. Otherwise, getservbyname matches both the name and the proto.
///
///
///
/// If no error occurs, getservbyname returns a pointer to the servent structure. Otherwise, it returns a null pointer
/// and a specific error number can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAHOST_NOT_FOUND
/// Authoritative Answer Service not found.
///
/// -
/// WSATRY_AGAIN
/// A nonauthoritative Service not found, or server failure.
///
/// -
/// WSANO_RECOVERY
/// Nonrecoverable errors, the services database is not accessible.
///
/// -
/// WSANO_DATA
/// Valid name, no data record of requested type.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEINTR
/// A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.
///
///
///
///
///
/// The getservbyname function returns a pointer to the servent structure containing the name(s) and service number that
/// match the string in the name parameter. All strings are null-terminated.
///
///
/// The pointer that is returned points to the servent structure allocated by the Windows Sockets library. The application
/// must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is
/// allocated per thread, so the application should copy any information it needs before issuing any other Windows Sockets function calls.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-getservbyname servent * getservbyname( const char *name,
// const char *proto );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Ansi)]
[PInvokeData("winsock.h", MSDNShortId = "730fa372-f620-4d21-99b9-3e7b79932792")]
public static extern IntPtr getservbyname(string name, [Optional] string proto);
/// The getservbyport function retrieves service information corresponding to a port and protocol.
/// Port for a service, in network byte order.
///
/// Optional pointer to a protocol name. If this is null, getservbyport returns the first service entry for which the port
/// matches the s_port of the servent structure. Otherwise, getservbyport matches both the port and the proto parameters.
///
///
///
/// If no error occurs, getservbyport returns a pointer to the servent structure. Otherwise, it returns a null pointer and a
/// specific error number can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAHOST_NOT_FOUND
/// Authoritative Answer Service not found.
///
/// -
/// WSATRY_AGAIN
/// A nonauthoritative Service not found, or server failure.
///
/// -
/// WSANO_RECOVERY
/// Nonrecoverable errors, the services database is not accessible.
///
/// -
/// WSANO_DATA
/// Valid name, no data record of requested type.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEFAULT
/// The proto parameter is not a valid part of the user address space.
///
/// -
/// WSAEINTR
/// A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.
///
///
///
///
/// The getservbyport function returns a pointer to a servent structure as it does in the getservbyname function.
///
/// The servent structure is allocated by Windows Sockets. The application must never attempt to modify this structure or to
/// free any of its components. Furthermore, only one copy of this structure is allocated per thread, so the application should copy
/// any information it needs before issuing any other Windows Sockets function calls.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-getservbyport servent * getservbyport( int port, const char
// *proto );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Ansi)]
[PInvokeData("winsock.h", MSDNShortId = "afd63c2d-4f77-49df-aeff-bfe56598fcbf")]
public static extern IntPtr getservbyport(int port, [Optional] string proto);
/// The getsockname function retrieves the local name for a socket.
/// Descriptor identifying a socket.
/// Pointer to a SOCKADDR structure that receives the address (name) of the socket.
/// Size of the name buffer, in bytes.
///
///
/// If no error occurs, getsockname returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code
/// can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this API.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEFAULT
/// The name or the namelen parameter is not a valid part of the user address space, or the namelen parameter is too small.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
/// -
/// WSAEINVAL
/// The socket has not been bound to an address with bind, or ADDR_ANY is specified in bind but connection has not yet occurred.
///
///
///
///
///
/// The getsockname function retrieves the current name for the specified socket descriptor in name. It is used on the bound
/// or connected socket specified by the s parameter. The local association is returned. This call is especially useful when a
/// connect call has been made without doing a bind first; the getsockname function provides the only way to determine the
/// local association that has been set by the system.
///
///
/// On call, the namelen parameter contains the size of the name buffer, in bytes. On return, the namelen parameter contains the
/// actual size in bytes of the name parameter.
///
///
/// The getsockname function does not always return information about the host address when the socket has been bound to an
/// unspecified address, unless the socket has been connected with connect or accept (for example, using ADDR_ANY). A Windows
/// Sockets application must not assume that the address will be specified unless the socket is connected. The address that will be
/// used for the socket is unknown unless the socket is connected when used in a multihomed host. If the socket is using a
/// connectionless protocol, the address may not be available until I/O occurs on the socket.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-getsockname int getsockname( SOCKET s, sockaddr *name,
// int *namelen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "be20a731-cdfc-48ae-90b2-43f2cf9ecf6d")]
public static extern int getsockname(SOCKET s, SOCKADDR name, ref int namelen);
/// The getsockopt function retrieves a socket option.
/// A descriptor identifying a socket.
/// The level at which the option is defined. Example: SOL_SOCKET.
///
/// The socket option for which the value is to be retrieved. Example: SO_ACCEPTCONN. The optname value must be a socket option
/// defined within the specified level, or behavior is undefined.
///
/// A pointer to the buffer in which the value for the requested option is to be returned.
/// A pointer to the size, in bytes, of the optval buffer.
///
///
/// If no error occurs, getsockopt returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code
/// can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
///
///
/// -
/// WSAEFAULT
///
/// One of the optval or the optlen parameters is not a valid part of the user address space, or the optlen parameter is too small.
///
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEINVAL
/// The level parameter is unknown or invalid.
///
/// -
/// WSAENOPROTOOPT
/// The option is unknown or unsupported by the indicated protocol family.
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
///
///
///
///
/// The getsockopt function retrieves the current value for a socket option associated with a socket of any type, in any
/// state, and stores the result in optval. Options can exist at multiple protocol levels, but they are always present at the
/// uppermost socket level. Options affect socket operations, such as the packet routing and OOB data transfer.
///
///
/// The value associated with the selected option is returned in the buffer optval. The integer pointed to by optlen should
/// originally contain the size of this buffer; on return, it will be set to the size of the value returned. For SO_LINGER, this
/// will be the size of a LINGER structure. For most other options, it will be the size of an integer.
///
///
/// The application is responsible for allocating any memory space pointed to directly or indirectly by any of the parameters it specified.
///
/// If the option was never set with setsockopt, then getsockopt returns the default value for the option.
/// The following options are supported for getsockopt. The Type column identifies the type of data addressed by optval.
/// For more information on socket options, see Socket Options.
/// The following table of value for the optname parameter are valid when the level parameter is set to SOL_SOCKET.
///
///
/// Value
/// Type
/// Meaning
///
/// -
/// SO_ACCEPTCONN
/// BOOL
/// The socket is listening.
///
/// -
/// SO_BROADCAST
/// BOOL
/// The socket is configured for the transmission and receipt of broadcast messages.
///
/// -
/// SO_BSP_STATE
/// CSADDR_INFO
/// Returns the local address, local port, remote address, remote port, socket type, and protocol used by a socket.
///
/// -
/// SO_CONDITIONAL_ACCEPT
/// BOOL
/// Returns current socket state, either from a previous call to setsockopt or the system default.
///
/// -
/// SO_CONNECT_TIME
/// DWORD
///
/// Returns the number of seconds a socket has been connected. This socket option is valid for connection oriented protocols only.
///
///
/// -
/// SO_DEBUG
/// BOOL
/// Debugging is enabled.
///
/// -
/// SO_DONTLINGER
/// BOOL
/// If TRUE, the SO_LINGER option is disabled.
///
/// -
/// SO_DONTROUTE
/// BOOL
///
/// Routing is disabled. Setting this succeeds but is ignored on AF_INET sockets; fails on AF_INET6 sockets with WSAENOPROTOOPT.
/// This option is not supported on ATM sockets.
///
///
/// -
/// SO_ERROR
/// int
/// Retrieves error status and clear.
///
/// -
/// SO_EXCLUSIVEADDRUSE
/// BOOL
/// Prevents any other socket from binding to the same address and port. This option must be set before calling the bind function.
///
/// -
/// SO_GROUP_ID
/// GROUP
/// Reserved.
///
/// -
/// SO_GROUP_PRIORITY
/// int
/// Reserved.
///
/// -
/// SO_KEEPALIVE
/// BOOL
/// Keep-alives are being sent. Not supported on ATM sockets.
///
/// -
/// SO_LINGER
/// LINGER structure
/// Returns the current linger options.
///
/// -
/// SO_MAX_MSG_SIZE
/// unsigned int
///
/// The maximum size of a message for message-oriented socket types (for example, SOCK_DGRAM). Has no meaning for stream oriented sockets.
///
///
/// -
/// SO_OOBINLINE
/// BOOL
///
/// OOB data is being received in the normal data stream. (See section Windows Sockets 1.1 Blocking Routines and EINPROGRESS for a
/// discussion of this topic.)
///
///
/// -
/// SO_PORT_SCALABILITY
/// BOOL
///
/// Enables local port scalability for a socket by allowing port allocation to be maximized by allocating wildcard ports multiple
/// times for different local address port pairs on a local machine.
///
///
/// -
/// SO_PROTOCOL_INFO
/// WSAPROTOCOL_INFO
/// A description of the protocol information for the protocol that is bound to this socket.
///
/// -
/// SO_RCVBUF
/// int
///
/// The total per-socket buffer space reserved for receives. This is unrelated to SO_MAX_MSG_SIZE and does not necessarily
/// correspond to the size of the TCP receive window.
///
///
/// -
/// SO_REUSEADDR
/// BOOL
/// The socket can be bound to an address which is already in use. Not applicable for ATM sockets.
///
/// -
/// SO_SNDBUF
/// int
///
/// The total per-socket buffer space reserved for sends. This is unrelated to SO_MAX_MSG_SIZE and does not necessarily correspond
/// to the size of a TCP send window.
///
///
/// -
/// SO_TYPE
/// int
/// The type of the socket (for example, SOCK_STREAM).
///
/// -
/// PVD_CONFIG
/// Service Provider Dependent
///
/// An opaque data structure object from the service provider associated with socket s. This object stores the current configuration
/// information of the service provider. The exact format of this data structure is service provider specific.
///
///
///
/// The following table of value for the optname parameter are valid when the level parameter is set to IPPROTO_TCP.
///
///
/// Value
/// Type
/// Meaning
///
/// -
/// TCP_NODELAY
/// BOOL
/// Disables the Nagle algorithm for send coalescing.
///
///
/// The following table of value for the optname parameter are valid when the level parameter is set to NSPROTO_IPX.
/// Note Windows NT supports all IPX options. Windows Me, Windows 98, and Windows 95 support only the following options:
///
///
/// Value
/// Type
/// Meaning
///
/// -
/// IPX_PTYPE
/// int
/// Retrieves the IPX packet type.
///
/// -
/// IPX_FILTERPTYPE
/// int
/// Retrieves the receive filter packet type
///
/// -
/// IPX_DSTYPE
/// int
/// Obtains the value of the data stream field in the SPX header on every packet sent.
///
/// -
/// IPX_EXTENDED_ADDRESS
/// BOOL
/// Finds out whether extended addressing is enabled.
///
/// -
/// IPX_RECVHDR
/// BOOL
/// Finds out whether the protocol header is sent up on all receive headers.
///
/// -
/// IPX_MAXSIZE
/// int
/// Obtains the maximum data size that can be sent.
///
/// -
/// IPX_ADDRESS
/// IPX_ADDRESS_DATA structure
///
/// Obtains information about a specific adapter to which IPX is bound. Adapter numbering is base zero. The adapternum member is
/// filled in upon return.
///
///
/// -
/// IPX_GETNETINFO
/// IPX_NETNUM_DATA structure
/// Obtains information about a specific IPX network number. If not available in the cache, uses RIP to obtain information.
///
/// -
/// IPX_GETNETINFO_NORIP
/// IPX_NETNUM_DATA structure
///
/// Obtains information about a specific IPX network number. If not available in the cache, will not use RIP to obtain information,
/// and returns error.
///
///
/// -
/// IPX_SPXGETCONNECTIONSTATUS
/// IPX_SPXCONNSTATUS_DATA structure
/// Retrieves information about a connected SPX socket.
///
/// -
/// IPX_ADDRESS_NOTIFY
/// IPX_ADDRESS_DATA structure
/// Retrieves status notification when changes occur on an adapter to which IPX is bound.
///
/// -
/// IPX_MAX_ADAPTER_NUM
/// int
/// Retrieves maximum number of adapters present, numbered as base zero.
///
/// -
/// IPX_RERIPNETNUMBER
/// IPX_NETNUM_DATA structure
/// Similar to IPX_GETNETINFO, but forces IPX to use RIP for resolution, even if the network information is in the local cache.
///
/// -
/// IPX_IMMEDIATESPXACK
/// BOOL
///
/// Directs SPX connections not to delay before sending an ACK. Applications without back-and-forth traffic should set this to TRUE
/// to increase performance.
///
///
/// -
/// TCP_MAXSEG
/// int
/// Receives TCP maximum-segment size. Supported in Windows 10 and newer versions.
///
///
///
/// The following table lists value for the optname that represent BSD socket options that are not supported by the
/// getsockopt function.
///
///
///
/// Value
/// Type
/// Meaning
///
/// -
/// SO_RCVLOWAT
/// int
/// Receives low watermark.
///
/// -
/// SO_RCVTIMEO
/// int
/// Receives time-out.
///
/// -
/// SO_SNDLOWAT
/// int
/// Sends low watermark.
///
/// -
/// SO_SNDTIMEO
/// int
/// Sends time-out.
///
/// -
/// TCP_MAXSEG
/// int
/// Receives TCP maximum-segment size. Not supported in versions before Windows 10.
///
///
///
/// Note When using the recv function, if no data arrives during the period specified in SO_RCVTIMEO, the recv
/// function completes. In Windows versions prior to Windows 2000, any data received subsequently fails with WSAETIMEDOUT. In
/// Windows 2000 and later, if no data arrives within the period specified in SO_RCVTIMEO, the recv function returns
/// WSAETIMEDOUT, and if data is received, recv returns SUCCESS.
///
///
/// Calling getsockopt with an unsupported option will result in an error code of WSAENOPROTOOPT being returned from WSAGetLastError.
///
///
/// More detailed information on some of the socket options for the optname parameter supported by the getsockopt function
/// are listed below.
///
///
/// Note When issuing a blocking Winsock call such as getsockopt, Winsock may need to wait for a network event before
/// the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous
/// procedure call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an
/// ongoing blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Example Code
/// The following code sample demonstrates the use of the getsockopt function.
/// Notes for IrDA Sockets
///
/// -
/// The Af_irda.h header file must be explicitly included.
///
/// -
///
/// Windows returns WSAENETDOWN to indicate the underlying transceiver driver failed to initialize with the IrDA protocol stack.
///
///
/// -
/// IrDA supports several special socket options:
///
///
///
/// Before an IrDA socket connection can be initiated, a device address must be obtained by performing a
/// getsockopt(,,IRLMP_ENUMDEVICES,,) function call, which returns a list of all available IrDA devices. A device address
/// returned from the function call is copied into a SOCKADDR_IRDA structure, which in turn is used by a subsequent call to the
/// connect function call.
///
/// Discovery can be performed in two ways:
///
/// -
///
/// First, performing a getsockopt function call with the IRLMP_ENUMDEVICES option causes a single discovery to be run on each idle
/// adapter. The list of discovered devices and cached devices (on active adapters) is returned immediately.
///
///
/// -
///
/// The second approach to performing discovery of IrDA device addresses is to perform a lazy discovery; in this approach, the
/// application is not notified until the discovered devices list changes from the last discovery run by the stack.
///
///
///
///
/// The DEVICELIST structure shown in the Type column in the previous table is an extendible array of device descriptions.
/// IrDA fills in as many device descriptions as can fit in the specified buffer. The device description consists of a device
/// identifier necessary to form a sockaddr_irda structure, and a displayable string describing the device.
///
///
/// The IAS_QUERY structure shown in the Type column in the previous table is used to retrieve a single attribute of a single
/// class from a peer device's IAS database. The application specifies the device and class to query and the attribute and attribute
/// type. Note that the device would have been obtained previously by a call to getsockopt(IRLMP_ENUMDEVICES). It is expected
/// that the application allocates a buffer, of the necessary size, for the returned parameters.
///
/// Many level socket options are not meaningful to IrDA; only SO_LINGER and SO_DONTLINGER are specifically supported.
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-getsockopt int getsockopt( SOCKET s, int level, int
// optname, char *optval, int *optlen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Ansi)]
[PInvokeData("winsock.h", MSDNShortId = "25bc511d-7a9f-41c1-8983-1af1e3f8bf2d")]
public static extern int getsockopt(SOCKET s, int level, int optname, [Optional] IntPtr optval, ref int optlen);
/// The htonl function converts a u_long from host to TCP/IP network byte order (which is big-endian).
/// A 32-bit number in host byte order.
/// The htonl function returns the value in TCP/IP's network byte order.
///
///
/// The htonl function takes a 32-bit number in host byte order and returns a 32-bit number in the network byte order used in
/// TCP/IP networks (the AF_INET or AF_INET6 address family).
///
///
/// The htonl function can be used to convert an IPv4 address in host byte order to the IPv4 address in network byte order.
/// This function does not do any checking to determine if the hostlong parameter is a valid IPv4 address.
///
///
/// The htonl function does not require that the Winsock DLL has previously been loaded with a successful call to the
/// WSAStartup function.
///
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-htonl u_long htonl( u_long hostlong );
[DllImport(Lib.Ws2_32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "e3a18c5e-7efb-43d9-9abc-9d573bbb1923")]
public static extern uint htonl(uint hostlong);
/// The htons function converts a u_short from host to TCP/IP network byte order (which is big-endian).
/// A 16-bit number in host byte order.
/// The htons function returns the value in TCP/IP network byte order.
///
///
/// The htons function takes a 16-bit number in host byte order and returns a 16-bit number in network byte order used in
/// TCP/IP networks (the AF_INET or AF_INET6 address family).
///
///
/// The htons function can be used to convert an IP port number in host byte order to the IP port number in network byte order.
///
///
/// The htons function does not require that the Winsock DLL has previously been loaded with a successful call to the
/// WSAStartup function.
///
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-htons u_short htons( u_short hostshort );
[DllImport(Lib.Ws2_32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "3dae2655-2b3c-41d9-9650-125ac393d64a")]
public static extern ushort htons(ushort hostshort);
///
/// The inet_addr function converts a string containing an IPv4 dotted-decimal address into a proper address for the IN_ADDR structure.
///
/// TBD
///
///
/// If no error occurs, the inet_addr function returns an unsigned long value containing a suitable binary representation of
/// the Internet address given.
///
///
/// If the string in the cp parameter does not contain a legitimate Internet address, for example if a portion of an "a.b.c.d"
/// address exceeds 255, then inet_addr returns the value INADDR_NONE.
///
///
/// On Windows Server 2003and later if the string in the cp parameter is an empty string, then inet_addr returns the value
/// INADDR_NONE. If NULL is passed in the cp parameter, then inet_addr returns the value INADDR_NONE.
///
///
/// On Windows XPand earlier if the string in the cp parameter is an empty string, then inet_addr returns the value
/// INADDR_ANY. If NULL is passed in the cp parameter, then inet_addr returns the value INADDR_NONE.
///
///
///
///
/// The inet_addr function interprets the character string specified by the cp parameter. This string represents a numeric
/// Internet address expressed in the Internet standard ".'' notation. The value returned is a number suitable for use as an
/// Internet address. All Internet addresses are returned in IP's network order (bytes ordered from left to right). If you pass in "
/// " (a space) to the inet_addr function, inet_addr returns zero.
///
///
/// On Windows Vista and later, the RtlIpv4StringToAddress function can be used to convert a string representation of an IPv4
/// address to a binary IPv4 address represented as an IN_ADDR structure. On Windows Vista and later, the RtlIpv6StringToAddress
/// function can be used to convert a string representation of an IPv6 address to a binary IPv6 address represented as an
/// IN6_ADDR structure.
///
/// Internet Addresses
/// Values specified using the ".'' notation take one of the following forms:
/// a.b.c.d a.b.c a.b a
///
/// When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the 4 bytes of an
/// Internet address. When an Internet address is viewed as a 32-bit integer quantity on the Intel architecture, the bytes referred
/// to above appear as "d.c.b.a''. That is, the bytes on an Intel processor are ordered from right to left.
///
///
/// The parts that make up an address in "." notation can be decimal, octal or hexadecimal as specified in the C language. Numbers
/// that start with "0x" or "0X" imply hexadecimal. Numbers that start with "0" imply octal. All other numbers are interpreted as decimal.
///
///
///
/// Internet address value
/// Meaning
///
/// -
/// "4.3.2.16"
/// Decimal
///
/// -
/// "004.003.002.020"
/// Octal
///
/// -
/// "0x4.0x3.0x2.0x10"
/// Hexadecimal
///
/// -
/// "4.003.002.0x10"
/// Mix
///
///
///
/// The inet_addr function supports the decimal, octal, hexadecimal, and mixed notations for the string passed in the cp parameter.
///
///
/// Note The following notations are only used by Berkeley software, and nowhere else on the Internet. For compatibility with
/// Berkeley software, the inet_addr function also supports the additional notations specified below.
///
///
/// When a three-part address is specified, the last part is interpreted as a 16-bit quantity and placed in the right-most 2 bytes
/// of the network address. This makes the three-part address format convenient for specifying Class B network addresses as "128.net.host''
///
///
/// When a two-part address is specified, the last part is interpreted as a 24-bit quantity and placed in the right-most 3 bytes of
/// the network address. This makes the two-part address format convenient for specifying Class A network addresses as "net.host''.
///
/// When only one part is given, the value is stored directly in the network address without any byte rearrangement.
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
/// Examples
/// The following code example shows how to use the inet_addr function.
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-inet_addr unsigned long WSAAPI inet_addr( const char *cp );
[DllImport(Lib.Ws2_32, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Ansi)]
[PInvokeData("winsock2.h", MSDNShortId = "7d6df658-9d83-45c7-97e7-b2a016a73847")]
public static extern uint inet_addr(string cp);
///
///
/// The inet_ntoa function converts an (Ipv4) Internet network address into an ASCII string in Internet standard
/// dotted-decimal format.
///
///
/// An Internet address structure
///
///
/// If no error occurs, inet_ntoa returns a character pointer to a static buffer containing the text address in standard ".''
/// notation. Otherwise, it returns NULL.
///
///
///
///
/// The inet_ntoa function takes an Internet address structure specified by the in parameter and returns a
/// NULL-terminated ASCII string that represents the address in "." (dot) notation as in "192.168.16.0", an example of an
/// IPv4 address in dotted-decimal notation. The string returned by inet_ntoa resides in memory that is allocated by Windows
/// Sockets. The application should not make any assumptions about the way in which the memory is allocated. The string returned is
/// guaranteed to be valid only until the next Windows Sockets function call is made within the same thread. Therefore, the data
/// should be copied before another Windows Sockets call is made.
///
///
/// The WSAAddressToString function can be used to convert a sockaddr structure containing an IPv4 address to a string
/// representation of an IPv4 address in Internet standard dotted-decimal notation. The advantage of the WSAAddressToString
/// function is that it supports both IPv4 and IPv6 addresses. Another advantage of the WSAAddressToString function is that
/// there are both ASCII and Unicode versions of this function.
///
///
/// On Windows Vista and later, the RtlIpv4AddressToString function can be used to convert an IPv4 address represented as an IN_ADDR
/// structure to a string representation of an IPv4 address in Internet standard dotted-decimal notation. On Windows Vista and
/// later, the RtlIpv6AddressToString function can be used to convert an IPv6 address represented as an IN6_ADDR structure to
/// a string representation of an IPv6 address.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/wsipv6ok/nf-wsipv6ok-inet_ntoa void inet_ntoa( a );
[DllImport(Lib.Ws2_32, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Ansi)]
[PInvokeData("wsipv6ok.h", MSDNShortId = "01cd32e7-a01d-40e8-afb5-69223d643a0e")]
public static extern StrPtrAnsi inet_ntoa(IN_ADDR a);
/// The ioctlsocket function controls the I/O mode of a socket.
/// A descriptor identifying a socket.
/// A command to perform on the socket s.
/// A pointer to a parameter for cmd.
///
///
/// Upon successful completion, the ioctlsocket returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific
/// error code can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAENOTSOCK
/// The descriptor s is not a socket.
///
/// -
/// WSAEFAULT
/// The argp parameter is not a valid part of the user address space.
///
///
///
///
///
/// The ioctlsocket function can be used on any socket in any state. It is used to set or retrieve some operating parameters
/// associated with the socket, independent of the protocol and communications subsystem. Here are the supported commands to use in
/// the cmd parameter and their semantics:
///
///
/// The WSAIoctl function is used to set or retrieve operating parameters associated with the socket, the transport protocol, or the
/// communications subsystem.
///
///
/// The WSAIoctl function is more powerful than the ioctlsocket function and supports a large number of possible
/// values for the operating parameters to set or retrieve.
///
/// Example Code
/// The following example demonstrates the use of the ioctlsocket function.
/// Compatibility
///
/// This ioctlsocket function performs only a subset of functions on a socket when compared to the ioctl function
/// found in Berkeley sockets. The ioctlsocket function has no command parameter equivalent to the FIOASYNC of ioctl,
/// and SIOCATMARK is the only socket-level command that is supported by ioctlsocket.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-ioctlsocket int ioctlsocket( SOCKET s, long cmd, u_long
// *argp );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "048fcb8d-acd3-4917-a997-dd133db399f8")]
public static extern int ioctlsocket(SOCKET s, int cmd, IntPtr argp);
/// The listen function places a socket in a state in which it is listening for an incoming connection.
/// A descriptor identifying a bound, unconnected socket.
///
///
/// The maximum length of the queue of pending connections. If set to SOMAXCONN, the underlying service provider responsible
/// for socket s will set the backlog to a maximum reasonable value. If set to SOMAXCONN_HINT(N) (where N is a number), the
/// backlog value will be N, adjusted to be within the range (200, 65535). Note that SOMAXCONN_HINT can be used to set the
/// backlog to a larger value than possible with SOMAXCONN.
///
///
/// SOMAXCONN_HINT is only supported by the Microsoft TCP/IP service provider. There is no standard provision to obtain the
/// actual backlog value.
///
///
///
///
/// If no error occurs, listen returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code
/// can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEADDRINUSE
///
/// The socket's local address is already in use and the socket was not marked to allow address reuse with SO_REUSEADDR. This error
/// usually occurs during execution of the bind function, but could be delayed until this function if the bind was to a partially
/// wildcard address (involving ADDR_ANY) and if a specific address needs to be committed at the time of this function.
///
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEINVAL
/// The socket has not been bound with bind.
///
/// -
/// WSAEISCONN
/// The socket is already connected.
///
/// -
/// WSAEMFILE
/// No more socket descriptors are available.
///
/// -
/// WSAENOBUFS
/// No buffer space is available.
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
/// -
/// WSAEOPNOTSUPP
/// The referenced socket is not of a type that supports the listen operation.
///
///
///
///
///
/// To accept connections, a socket is first created with the socket function and bound to a local address with the bind function. A
/// backlog for incoming connections is specified with listen, and then the connections are accepted with the accept
/// function. Sockets that are connection oriented, those of type SOCK_STREAM for example, are used with listen. The
/// socket s is put into passive mode where incoming connection requests are acknowledged and queued pending acceptance by the process.
///
///
/// A value for the backlog of SOMAXCONN is a special constant that instructs the underlying service provider responsible for
/// socket s to set the length of the queue of pending connections to a maximum reasonable value.
///
/// On Windows Sockets 2, this maximum value defaults to a large value (typically several hundred or more).
///
/// When calling the listen function in a Bluetooth application, it is strongly recommended that a much lower value be used
/// for the backlog parameter (typically 2 to 4), since only a few client connections are accepted. This reduces the system
/// resources that are allocated for use by the listening socket. This same recommendation applies to other network applications
/// that expect only a few client connections.
///
///
/// The listen function is typically used by servers that can have more than one connection request at a time. If a
/// connection request arrives and the queue is full, the client will receive an error with an indication of WSAECONNREFUSED.
///
///
/// If there are no available socket descriptors, listen attempts to continue to function. If descriptors become available, a
/// later call to listen or accept will refill the queue to the current or most recent value specified for the backlog
/// parameter, if possible, and resume listening for incoming connections.
///
///
/// If the listen function is called on an already listening socket, it will return success without changing the value for
/// the backlog parameter. Setting the backlog parameter to 0 in a subsequent call to listen on a listening socket is not
/// considered a proper reset, especially if there are connections on the socket.
///
///
/// Note When issuing a blocking Winsock call such as listen, Winsock may need to wait for a network event before the
/// call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure
/// call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing
/// blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Example Code
/// The following example demonstrates the use of the listen function.
/// Example Code
/// For another example that uses the listen function, see Getting Started With Winsock.
/// Notes for IrDA Sockets
///
/// -
/// The Af_irda.h header file must be explicitly included.
///
///
/// Compatibility
///
/// The backlog parameter is limited (silently) to a reasonable value as determined by the underlying service provider. Illegal
/// values are replaced by the nearest legal value. There is no standard provision to find out the actual backlog value.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-listen int WSAAPI listen( SOCKET s, int backlog );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock2.h", MSDNShortId = "1233feeb-a8c1-49ac-ab34-82af224ecf00")]
public static extern int listen(SOCKET s, int backlog);
///
/// The ntohl function converts a u_long from TCP/IP network order to host byte order (which is little-endian on Intel processors).
///
/// A 32-bit number in TCP/IP network byte order.
///
/// The ntohl function returns the value supplied in the netlong parameter with the byte order reversed. If netlong is
/// already in host byte order, then this function will reverse it. It is up to the application to determine if the byte order must
/// be reversed.
///
///
///
/// The ntohl function takes a 32-bit number in TCP/IP network byte order (the AF_INET or AF_INET6 address family) and
/// returns a 32-bit number in host byte order.
///
///
/// The ntohl function can be used to convert an IPv4 address in network byte order to the IPv4 address in host byte order.
/// This function does not do any checking to determine if the netlong parameter is a valid IPv4 address.
///
///
/// The ntohl function does not require that the Winsock DLL has previously been loaded with a successful call to the
/// WSAStartup function.
///
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-ntohl u_long ntohl( u_long netlong );
[DllImport(Lib.Ws2_32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "04673bef-22c6-424f-a5ae-689fb648b54e")]
public static extern uint ntohl(uint netlong);
///
/// The ntohs function converts a u_short from TCP/IP network byte order to host byte order (which is little-endian on
/// Intel processors).
///
/// A 16-bit number in TCP/IP network byte order.
///
/// The ntohs function returns the value in host byte order. If the netshort parameter is already in host byte order, then
/// this function will reverse it. It is up to the application to determine if the byte order must be reversed.
///
///
///
/// The ntohs function takes a 16-bit number in TCP/IP network byte order (the AF_INET or AF_INET6 address family) and
/// returns a 16-bit number in host byte order.
///
///
/// The ntohs function can be used to convert an IP port number in network byte order to the IP port number in host byte order.
///
///
/// The ntohs function does not require that the Winsock DLL has previously been loaded with a successful call to the
/// WSAStartup function.
///
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-ntohs u_short ntohs( u_short netshort );
[DllImport(Lib.Ws2_32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "9946df13-3b40-4bcb-91ca-10684b3fc9a5")]
public static extern ushort ntohs(ushort netshort);
/// The recv function receives data from a connected socket or a bound connectionless socket.
/// The descriptor that identifies a connected socket.
/// A pointer to the buffer to receive the incoming data.
/// The length, in bytes, of the buffer pointed to by the buf parameter.
///
/// A set of flags that influences the behavior of this function. See remarks below. See the Remarks section for details on the
/// possible value for this parameter.
///
///
///
/// If no error occurs, recv returns the number of bytes received and the buffer pointed to by the buf parameter will contain
/// this data received. If the connection has been gracefully closed, the return value is zero.
///
/// Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEFAULT
/// The buf parameter is not completely contained in a valid part of the user address space.
///
/// -
/// WSAENOTCONN
/// The socket is not connected.
///
/// -
/// WSAEINTR
/// The (blocking) call was canceled through WSACancelBlockingCall.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAENETRESET
///
/// For a connection-oriented socket, this error indicates that the connection has been broken due to keep-alive activity that
/// detected a failure while the operation was in progress. For a datagram socket, this error indicates that the time to live has expired.
///
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
/// -
/// WSAEOPNOTSUPP
///
/// MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the
/// communication domain associated with this socket, or the socket is unidirectional and supports only send operations.
///
///
/// -
/// WSAESHUTDOWN
///
/// The socket has been shut down; it is not possible to receive on a socket after shutdown has been invoked with how set to
/// SD_RECEIVE or SD_BOTH.
///
///
/// -
/// WSAEWOULDBLOCK
/// The socket is marked as nonblocking and the receive operation would block.
///
/// -
/// WSAEMSGSIZE
/// The message was too large to fit into the specified buffer and was truncated.
///
/// -
/// WSAEINVAL
///
/// The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with
/// SO_OOBINLINE enabled or (for byte stream sockets only) len was zero or negative.
///
///
/// -
/// WSAECONNABORTED
///
/// The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no
/// longer usable.
///
///
/// -
/// WSAETIMEDOUT
/// The connection has been dropped because of a network failure or because the peer system failed to respond.
///
/// -
/// WSAECONNRESET
///
/// The virtual circuit was reset by the remote side executing a hard or abortive close. The application should close the socket as
/// it is no longer usable. On a UDP-datagram socket, this error would indicate that a previous send operation resulted in an ICMP
/// "Port Unreachable" message.
///
///
///
///
///
///
/// The recv function is used to read incoming data on connection-oriented sockets, or connectionless sockets. When using a
/// connection-oriented protocol, the sockets must be connected before calling recv. When using a connectionless protocol,
/// the sockets must be bound before calling recv.
///
///
/// The local address of the socket must be known. For server applications, use an explicit bind function or an implicit accept or
/// WSAAccept function. Explicit binding is discouraged for client applications. For client applications, the socket can become
/// bound implicitly to a local address using connect, WSAConnect, sendto, WSASendTo, or WSAJoinLeaf.
///
///
/// For connected or connectionless sockets, the recv function restricts the addresses from which received messages are
/// accepted. The function only returns messages from the remote address specified in the connection. Messages from other addresses
/// are (silently) discarded.
///
///
/// For connection-oriented sockets (type SOCK_STREAM for example), calling recv will return as much data as is currently
/// available—up to the size of the buffer specified. If the socket has been configured for in-line reception of OOB data (socket
/// option SO_OOBINLINE) and OOB data is yet unread, only OOB data will be returned. The application can use the ioctlsocket or
/// WSAIoctl SIOCATMARK command to determine whether any more OOB data remains to be read.
///
///
/// For connectionless sockets (type SOCK_DGRAM or other message-oriented sockets), data is extracted from the first enqueued
/// datagram (message) from the destination address specified by the connect function.
///
///
/// If the datagram or message is larger than the buffer specified, the buffer is filled with the first part of the datagram, and
/// recv generates the error WSAEMSGSIZE. For unreliable protocols (for example, UDP) the excess data is lost; for reliable
/// protocols, the data is retained by the service provider until it is successfully read by calling recv with a large enough buffer.
///
///
/// If no incoming data is available at the socket, the recv call blocks and waits for data to arrive according to the
/// blocking rules defined for WSARecv with the MSG_PARTIAL flag not set unless the socket is nonblocking. In this case, a value of
/// SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The select, WSAAsyncSelect, or WSAEventSelect functions can
/// be used to determine when more data arrives.
///
///
/// If the socket is connection oriented and the remote side has shut down the connection gracefully, and all data has been
/// received, a recv will complete immediately with zero bytes received. If the connection has been reset, a recv will
/// fail with the error WSAECONNRESET.
///
///
/// The flags parameter can be used to influence the behavior of the function invocation beyond the options specified for the
/// associated socket. The semantics of this function are determined by the socket options and the flags parameter. The possible
/// value of flags parameter is constructed by using the bitwise OR operator with any of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// MSG_PEEK
///
/// Peeks at the incoming data. The data is copied into the buffer, but is not removed from the input queue. The function
/// subsequently returns the amount of data that can be read in a single call to the recv (or recvfrom) function, which may not be
/// the same as the total amount of data queued on the socket. The amount of data that can actually be read in a single call to the
/// recv (or recvfrom) function is limited to the data size written in the send or sendto function call.
///
///
/// -
/// MSG_OOB
/// Processes Out Of Band (OOB) data.
///
/// -
/// MSG_WAITALL
///
/// The receive request will complete only when one of the following events occurs:Note that if the underlying transport does not
/// support MSG_WAITALL, or if the socket is in a non-blocking mode, then this call will fail with WSAEOPNOTSUPP. Also, if
/// MSG_WAITALL is specified along with MSG_OOB, MSG_PEEK, or MSG_PARTIAL, then this call will fail with WSAEOPNOTSUPP. This flag is
/// not supported on datagram sockets or message-oriented sockets.
///
///
///
///
/// Note When issuing a blocking Winsock call such as recv, Winsock may need to wait for a network event before the
/// call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure
/// call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing
/// blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Example Code
/// The following code example shows the use of the recv function.
/// Example Code
/// For more information, and another example of the recv function, see Getting Started With Winsock.
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-recv int recv( SOCKET s, char *buf, int len, int flags );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "8c247cd3-479f-45d0-a038-a24e80cc7c73")]
public static extern int recv(SOCKET s, IntPtr buf, int len, MsgFlags flags);
/// The recvfrom function receives a datagram and stores the source address.
/// A descriptor identifying a bound socket.
/// A buffer for the incoming data.
/// The length, in bytes, of the buffer pointed to by the buf parameter.
///
/// A set of options that modify the behavior of the function call beyond the options specified for the associated socket. See the
/// Remarks below for more details.
///
/// An optional pointer to a buffer in a sockaddr structure that will hold the source address upon return.
/// An optional pointer to the size, in bytes, of the buffer pointed to by the from parameter.
///
///
/// If no error occurs, recvfrom returns the number of bytes received. If the connection has been gracefully closed, the
/// return value is zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEFAULT
///
/// The buffer pointed to by the buf or from parameters are not in the user address space, or the fromlen parameter is too small to
/// accommodate the source address of the peer address.
///
///
/// -
/// WSAEINTR
/// The (blocking) call was canceled through WSACancelBlockingCall.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEINVAL
///
/// The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with
/// SO_OOBINLINE enabled, or (for byte stream-style sockets only) len was zero or negative.
///
///
/// -
/// WSAEISCONN
///
/// The socket is connected. This function is not permitted with a connected socket, whether the socket is connection oriented or connectionless.
///
///
/// -
/// WSAENETRESET
/// For a datagram socket, this error indicates that the time to live has expired.
///
/// -
/// WSAENOTSOCK
/// The descriptor in the s parameter is not a socket.
///
/// -
/// WSAEOPNOTSUPP
///
/// MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the
/// communication domain associated with this socket, or the socket is unidirectional and supports only send operations.
///
///
/// -
/// WSAESHUTDOWN
///
/// The socket has been shut down; it is not possible to recvfrom on a socket after shutdown has been invoked with how set to
/// SD_RECEIVE or SD_BOTH.
///
///
/// -
/// WSAEWOULDBLOCK
/// The socket is marked as nonblocking and the recvfrom operation would block.
///
/// -
/// WSAEMSGSIZE
/// The message was too large to fit into the buffer pointed to by the buf parameter and was truncated.
///
/// -
/// WSAETIMEDOUT
///
/// The connection has been dropped, because of a network failure or because the system on the other end went down without notice.
///
///
/// -
/// WSAECONNRESET
///
/// The virtual circuit was reset by the remote side executing a hard or abortive close. The application should close the socket; it
/// is no longer usable. On a UDP-datagram socket this error indicates a previous send operation resulted in an ICMP Port
/// Unreachable message.
///
///
///
///
///
///
/// The recvfrom function reads incoming data on both connected and unconnected sockets and captures the address from which
/// the data was sent. This function is typically used with connectionless sockets. The local address of the socket must be known.
/// For server applications, this is usually done explicitly through bind. Explicit binding is discouraged for client applications.
/// For client applications using this function, the socket can become bound implicitly to a local address through sendto,
/// WSASendTo, or WSAJoinLeaf.
///
///
/// For stream-oriented sockets such as those of type SOCK_STREAM, a call to recvfrom returns as much information as is
/// currently available—up to the size of the buffer specified. If the socket has been configured for inline reception of OOB data
/// (socket option SO_OOBINLINE) and OOB data is yet unread, only OOB data will be returned. The application can use the ioctlsocket
/// or WSAIoctl SIOCATMARK command to determine whether any more OOB data remains to be read. The from and fromlen parameters
/// are ignored for connection-oriented sockets.
///
///
/// For message-oriented sockets, data is extracted from the first enqueued message, up to the size of the buffer specified. If the
/// datagram or message is larger than the buffer specified, the buffer is filled with the first part of the datagram, and
/// recvfrom generates the error WSAEMSGSIZE. For unreliable protocols (for example, UDP) the excess data is lost. For UDP if
/// the packet received contains no data (empty), the return value from the recvfrom function function is zero.
///
///
/// If the from parameter is nonzero and the socket is not connection oriented, (type SOCK_DGRAM for example), the network address
/// of the peer that sent the data is copied to the corresponding sockaddr structure. The value pointed to by fromlen is initialized
/// to the size of this structure and is modified, on return, to indicate the actual size of the address stored in the
/// sockaddr structure.
///
///
/// If no incoming data is available at the socket, the recvfrom function blocks and waits for data to arrive according to
/// the blocking rules defined for WSARecv with the MSG_PARTIAL flag not set unless the socket is nonblocking. In this case, a value
/// of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The select, WSAAsyncSelect, or WSAEventSelect can be used
/// to determine when more data arrives.
///
///
/// If the socket is connection oriented and the remote side has shut down the connection gracefully, the call to recvfrom
/// will complete immediately with zero bytes received. If the connection has been reset recvfrom will fail with the error WSAECONNRESET.
///
///
/// The flags parameter can be used to influence the behavior of the function invocation beyond the options specified for the
/// associated socket. The semantics of this function are determined by the socket options and the flags parameter. The latter is
/// constructed by using the bitwise OR operator with any of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// MSG_PEEK
///
/// Peeks at the incoming data. The data is copied into the buffer but is not removed from the input queue. The function
/// subsequently returns the amount of data that can be read in a single call to the recvfrom (or recv) function, which may not be
/// the same as the total amount of data queued on the socket. The amount of data that can actually be read in a single call to the
/// recvfrom (or recv) function is limited to the data size written in the send or sendto function call.
///
///
/// -
/// MSG_OOB
/// Processes Out Of Band (OOB) data.
///
///
///
/// Note When issuing a blocking Winsock call such as recvfrom, Winsock may need to wait for a network event before
/// the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous
/// procedure call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an
/// ongoing blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Example Code
/// The following example demonstrates the use of the recvfrom function.
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-recvfrom int recvfrom( SOCKET s, char *buf, int len, int
// flags, sockaddr *from, int *fromlen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "3e4282e0-3ed0-43e7-9b27-72ec36b9cfa1")]
public static extern int recvfrom(SOCKET s, IntPtr buf, int len, int flags, SOCKADDR from, ref int fromlen);
/// The send function sends data on a connected socket.
/// A descriptor identifying a connected socket.
/// A pointer to a buffer containing the data to be transmitted.
/// The length, in bytes, of the data in buffer pointed to by the buf parameter.
///
///
/// A set of flags that specify the way in which the call is made. This parameter is constructed by using the bitwise OR operator
/// with any of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// MSG_DONTROUTE
///
/// Specifies that the data should not be subject to routing. A Windows Sockets service provider can choose to ignore this flag.
///
///
/// -
/// MSG_OOB
/// Sends OOB data (stream-style socket such as SOCK_STREAM only.
///
///
///
///
///
/// If no error occurs, send returns the total number of bytes sent, which can be less than the number requested to be sent
/// in the len parameter. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEACCES
///
/// The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST socket
/// option to enable use of the broadcast address.
///
///
/// -
/// WSAEINTR
/// A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEFAULT
/// The buf parameter is not completely contained in a valid part of the user address space.
///
/// -
/// WSAENETRESET
/// The connection has been broken due to the keep-alive activity detecting a failure while the operation was in progress.
///
/// -
/// WSAENOBUFS
/// No buffer space is available.
///
/// -
/// WSAENOTCONN
/// The socket is not connected.
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
/// -
/// WSAEOPNOTSUPP
///
/// MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the
/// communication domain associated with this socket, or the socket is unidirectional and supports only receive operations.
///
///
/// -
/// WSAESHUTDOWN
///
/// The socket has been shut down; it is not possible to send on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
///
///
/// -
/// WSAEWOULDBLOCK
/// The socket is marked as nonblocking and the requested operation would block.
///
/// -
/// WSAEMSGSIZE
/// The socket is message oriented, and the message is larger than the maximum supported by the underlying transport.
///
/// -
/// WSAEHOSTUNREACH
/// The remote host cannot be reached from this host at this time.
///
/// -
/// WSAEINVAL
///
/// The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with
/// SO_OOBINLINE enabled.
///
///
/// -
/// WSAECONNABORTED
///
/// The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no
/// longer usable.
///
///
/// -
/// WSAECONNRESET
///
/// The virtual circuit was reset by the remote side executing a hard or abortive close. For UDP sockets, the remote host was unable
/// to deliver a previously sent UDP datagram and responded with a "Port Unreachable" ICMP packet. The application should close the
/// socket as it is no longer usable.
///
///
/// -
/// WSAETIMEDOUT
///
/// The connection has been dropped, because of a network failure or because the system on the other end went down without notice.
///
///
///
///
///
/// The send function is used to write outgoing data on a connected socket.
///
/// For message-oriented sockets (address family of AF_INET or AF_INET6, type of SOCK_DGRAM, and protocol of
/// IPPROTO_UDP, for example), care must be taken not to exceed the maximum packet size of the underlying provider. The
/// maximum message packet size for a provider can be obtained by calling getsockopt with the optname parameter set to
/// SO_MAX_MSG_SIZE to retrieve the value of socket option. If the data is too long to pass atomically through the underlying
/// protocol, the error WSAEMSGSIZE is returned, and no data is transmitted.
///
///
/// The successful completion of a send function does not indicate that the data was successfully delivered and received to
/// the recipient. This function only indicates the data was successfully sent.
///
///
/// If no buffer space is available within the transport system to hold the data to be transmitted, send will block unless
/// the socket has been placed in nonblocking mode. On nonblocking stream oriented sockets, the number of bytes written can be
/// between 1 and the requested length, depending on buffer availability on both the client and server computers. The select,
/// WSAAsyncSelect or WSAEventSelect functions can be used to determine when it is possible to send more data.
///
///
/// Calling send with a len parameter of zero is permissible and will be treated by implementations as successful. In such
/// cases, send will return zero as a valid value. For message-oriented sockets, a zero-length transport datagram is sent.
///
///
/// The flags parameter can be used to influence the behavior of the function beyond the options specified for the associated
/// socket. The semantics of the send function are determined by any options previously set on the socket specified in the s
/// parameter and the flags parameter passed to the send function.
///
///
/// The order of calls made to send is also the order in which the buffers are transmitted to the transport layer.
/// send should not be called on the same stream-oriented socket concurrently from different threads, because some Winsock
/// providers may split a large send request into multiple transmissions, and this may lead to unintended data interleaving from
/// multiple concurrent send requests on the same stream-oriented socket.
///
///
/// Note When issuing a blocking Winsock call such as send, Winsock may need to wait for a network event before the
/// call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure
/// call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing
/// blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Example Code
/// The following example demonstrates the use of the send function.
/// Example Code
/// For a another example that uses the send function, see Getting Started With Winsock.
/// Notes for IrDA Sockets
///
/// -
/// The Af_irda.h header file must be explicitly included.
///
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-send int WSAAPI send( SOCKET s, const char *buf, int len,
// int flags );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock2.h", MSDNShortId = "902bb9cf-d847-43fc-8282-394d619b8f1b")]
public static extern int send(SOCKET s, IntPtr buf, int len, int flags);
/// The sendto function sends data to a specific destination.
/// A descriptor identifying a (possibly connected) socket.
/// A pointer to a buffer containing the data to be transmitted.
/// The length, in bytes, of the data pointed to by the buf parameter.
/// A set of flags that specify the way in which the call is made.
/// An optional pointer to a sockaddr structure that contains the address of the target socket.
/// The size, in bytes, of the address pointed to by the to parameter.
///
///
/// If no error occurs, sendto returns the total number of bytes sent, which can be less than the number indicated by len.
/// Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEACCES
///
/// The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST
/// parameter to allow the use of the broadcast address.
///
///
/// -
/// WSAEINVAL
/// An unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled.
///
/// -
/// WSAEINTR
/// A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEFAULT
/// The buf or to parameters are not part of the user address space, or the tolen parameter is too small.
///
/// -
/// WSAENETRESET
/// The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress.
///
/// -
/// WSAENOBUFS
/// No buffer space is available.
///
/// -
/// WSAENOTCONN
/// The socket is not connected (connection-oriented sockets only).
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
/// -
/// WSAEOPNOTSUPP
///
/// MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the
/// communication domain associated with this socket, or the socket is unidirectional and supports only receive operations.
///
///
/// -
/// WSAESHUTDOWN
///
/// The socket has been shut down; it is not possible to sendto on a socket after shutdown has been invoked with how set to SD_SEND
/// or SD_BOTH.
///
///
/// -
/// WSAEWOULDBLOCK
/// The socket is marked as nonblocking and the requested operation would block.
///
/// -
/// WSAEMSGSIZE
/// The socket is message oriented, and the message is larger than the maximum supported by the underlying transport.
///
/// -
/// WSAEHOSTUNREACH
/// The remote host cannot be reached from this host at this time.
///
/// -
/// WSAECONNABORTED
///
/// The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no
/// longer usable.
///
///
/// -
/// WSAECONNRESET
///
/// The virtual circuit was reset by the remote side executing a hard or abortive close. For UPD sockets, the remote host was unable
/// to deliver a previously sent UDP datagram and responded with a "Port Unreachable" ICMP packet. The application should close the
/// socket as it is no longer usable.
///
///
/// -
/// WSAEADDRNOTAVAIL
/// The remote address is not a valid address, for example, ADDR_ANY.
///
/// -
/// WSAEAFNOSUPPORT
/// Addresses in the specified family cannot be used with this socket.
///
/// -
/// WSAEDESTADDRREQ
/// A destination address is required.
///
/// -
/// WSAENETUNREACH
/// The network cannot be reached from this host at this time.
///
/// -
/// WSAEHOSTUNREACH
/// A socket operation was attempted to an unreachable host.
///
/// -
/// WSAETIMEDOUT
///
/// The connection has been dropped, because of a network failure or because the system on the other end went down without notice.
///
///
///
///
///
///
/// The sendto function is used to write outgoing data on a socket. For message-oriented sockets, care must be taken not to
/// exceed the maximum packet size of the underlying subnets, which can be obtained by using getsockopt to retrieve the value of
/// socket option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying protocol, the error WSAEMSGSIZE
/// is returned and no data is transmitted.
///
///
/// The to parameter can be any valid address in the socket's address family, including a broadcast or any multicast address. To
/// send to a broadcast address, an application must have used setsockopt with SO_BROADCAST enabled. Otherwise, sendto will
/// fail with the error code WSAEACCES. For TCP/IP, an application can send to any multicast address (without becoming a group member).
///
///
/// Note If a socket is opened, a setsockopt call is made, and then a sendto call is made, Windows Sockets performs an
/// implicit bind function call.
///
///
/// If the socket is unbound, unique values are assigned to the local association by the system, and the socket is then marked as
/// bound. If the socket is connected, the getsockname function can be used to determine the local IP address and port associated
/// with the socket.
///
///
/// If the socket is not connected, the getsockname function can be used to determine the local port number associated with the
/// socket but the IP address returned is set to the wildcard address for the given protocol (for example, INADDR_ANY or "0.0.0.0"
/// for IPv4 and IN6ADDR_ANY_INIT or "::" for IPv6).
///
/// The successful completion of a sendto does not indicate that the data was successfully delivered.
///
/// The sendto function is normally used on a connectionless socket to send a datagram to a specific peer socket identified
/// by the to parameter. Even if the connectionless socket has been previously connected to a specific address, the to parameter
/// overrides the destination address for that particular datagram only. On a connection-oriented socket, the to and tolen
/// parameters are ignored, making sendto equivalent to send.
///
///
/// Note When issuing a blocking Winsock call such as sendto, Winsock may need to wait for a network event before the
/// call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure
/// call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing
/// blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Example Code
/// The following example demonstrates the use of the sendto function.
/// For Sockets Using IP (Version 4)
///
/// To send a broadcast (on a SOCK_DGRAM only), the address pointed to by the to parameter can be constructed to contain the special
/// IPv4 address INADDR_BROADCAST (defined in Winsock2.h), together with the intended port number. If the address pointed to by the
/// to parameter contains the INADDR_BROADCAST address and intended port, then the broadcast will be sent out on all interfaces to
/// that port.
///
///
/// If the broadcast should be sent out only on a specific interface, then the address pointed to by the to parameter should contain
/// the subnet broadcast address for the interface and the intended port. For example, an IPv4 network address of 192.168.1.0 with a
/// subnet mask of 255.255.255.0 would use a subnet broadcast address of 192.168.1.255.
///
///
/// It is generally inadvisable for a broadcast datagram to exceed the size at which fragmentation can occur, which implies that the
/// data portion of the datagram (excluding headers) should not exceed 512 bytes.
///
///
/// If no buffer space is available within the transport system to hold the data to be transmitted, sendto will block unless
/// the socket has been placed in a nonblocking mode. On nonblocking, stream oriented sockets, the number of bytes written can be
/// between 1 and the requested length, depending on buffer availability on both the client and server systems. The select,
/// WSAAsyncSelect or WSAEventSelect function can be used to determine when it is possible to send more data.
///
///
/// Calling sendto with a len of zero is permissible and will return zero as a valid value. For message-oriented sockets, a
/// zero-length transport datagram is sent.
///
///
/// The flags parameter can be used to influence the behavior of the function invocation beyond the options specified for the
/// associated socket. The semantics of this function are determined by the socket options and the flags parameter. The latter is
/// constructed by using the bitwise OR operator with any of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// MSG_DONTROUTE
///
/// Specifies that the data should not be subject to routing. A Windows Sockets service provider can choose to ignore this flag.
///
///
/// -
/// MSG_OOB
/// Sends OOB data (stream-style socket such as SOCK_STREAM only).
///
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-sendto int sendto( SOCKET s, const char *buf, int len, int
// flags, const sockaddr *to, int tolen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "a1c89c6b-d11d-4d3e-a664-af2beed0cd09")]
public static extern int sendto(SOCKET s, IntPtr buf, int len, int flags, SOCKADDR to, int tolen);
/// The setsockopt function sets a socket option.
/// A descriptor that identifies a socket.
/// The level at which the option is defined (for example, SOL_SOCKET).
///
/// The socket option for which the value is to be set (for example, SO_BROADCAST). The optname parameter must be a socket option
/// defined within the specified level, or behavior is undefined.
///
/// A pointer to the buffer in which the value for the requested option is specified.
/// The size, in bytes, of the buffer pointed to by the optval parameter.
///
///
/// If no error occurs, setsockopt returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code
/// can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAEFAULT
///
/// The buffer pointed to by the optval parameter is not in a valid part of the process address space or the optlen parameter is too small.
///
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEINVAL
/// The level parameter is not valid, or the information in the buffer pointed to by the optval parameter is not valid.
///
/// -
/// WSAENETRESET
/// The connection has timed out when SO_KEEPALIVE is set.
///
/// -
/// WSAENOPROTOOPT
/// The option is unknown or unsupported for the specified provider or socket (see SO_GROUP_PRIORITY limitations).
///
/// -
/// WSAENOTCONN
/// The connection has been reset when SO_KEEPALIVE is set.
///
/// -
/// WSAENOTSOCK
/// The descriptor is not a socket.
///
///
///
///
///
/// The setsockopt function sets the current value for a socket option associated with a socket of any type, in any state.
/// Although options can exist at multiple protocol levels, they are always present at the uppermost socket level. Options affect
/// socket operations, such as whether expedited data (OOB data for example) is received in the normal data stream, and whether
/// broadcast messages can be sent on the socket.
///
///
/// Note If the setsockopt function is called before the bind function, TCP/IP options will not be checked by using
/// TCP/IP until the bind occurs. In this case, the setsockopt function call will always succeed, but the bind
/// function call can fail because of an early setsockopt call failing.
///
///
/// Note If a socket is opened, a setsockopt call is made, and then a sendto call is made, Windows Sockets performs an
/// implicit bind function call.
///
///
/// There are two types of socket options: Boolean options that enable or disable a feature or behavior, and options that require an
/// integer value or structure. To enable a Boolean option, the optval parameter points to a nonzero integer. To disable the option
/// optval points to an integer equal to zero. The optlen parameter should be equal to for Boolean options. For other options,
/// optval points to an integer or structure that contains the desired value for the option, and optlen is the length of the integer
/// or structure.
///
///
/// The following tables list some of the common options supported by the setsockopt function. The Type column identifies the
/// type of data addressed by optval parameter. The Description column provides some basic information about the socket option. For
/// more complete lists of socket options and more detailed information (default values, for example), see the detailed topics under
/// Socket Options.
///
/// level = SOL_SOCKET
///
///
/// Value
/// Type
/// Description
///
/// -
/// SO_BROADCAST
/// BOOL
/// Configures a socket for sending broadcast data.
///
/// -
/// SO_CONDITIONAL_ACCEPT
/// BOOL
/// Enables incoming connections are to be accepted or rejected by the application, not by the protocol stack.
///
/// -
/// SO_DEBUG
/// BOOL
/// Enables debug output. Microsoft providers currently do not output any debug information.
///
/// -
/// SO_DONTLINGER
/// BOOL
///
/// Does not block close waiting for unsent data to be sent. Setting this option is equivalent to setting SO_LINGER with l_onoff set
/// to zero.
///
///
/// -
/// SO_DONTROUTE
/// BOOL
///
/// Sets whether outgoing data should be sent on interface the socket is bound to and not a routed on some other interface. This
/// option is not supported on ATM sockets (results in an error).
///
///
/// -
/// SO_GROUP_PRIORITY
/// int
/// Reserved.
///
/// -
/// SO_KEEPALIVE
/// BOOL
/// Enables sending keep-alive packets for a socket connection. Not supported on ATM sockets (results in an error).
///
/// -
/// SO_LINGER
/// LINGER
/// Lingers on close if unsent data is present.
///
/// -
/// SO_OOBINLINE
/// BOOL
///
/// Indicates that out-of-bound data should be returned in-line with regular data. This option is only valid for connection-oriented
/// protocols that support out-of-band data. For a discussion of this topic, see Protocol Independent Out-Of-band Data.
///
///
/// -
/// SO_RCVBUF
/// int
/// Specifies the total per-socket buffer space reserved for receives.
///
/// -
/// SO_REUSEADDR
/// BOOL
///
/// Allows the socket to be bound to an address that is already in use. For more information, see bind. Not applicable on ATM sockets.
///
///
/// -
/// SO_EXCLUSIVEADDRUSE
/// BOOL
/// Enables a socket to be bound for exclusive access. Does not require administrative privilege.
///
/// -
/// SO_RCVTIMEO
/// DWORD
/// Sets the timeout, in milliseconds, for blocking receive calls.
///
/// -
/// SO_SNDBUF
/// int
/// Specifies the total per-socket buffer space reserved for sends.
///
/// -
/// SO_SNDTIMEO
/// DWORD
/// The timeout, in milliseconds, for blocking send calls.
///
/// -
/// SO_UPDATE_ACCEPT_CONTEXT
/// int
/// Updates the accepting socket with the context of the listening socket.
///
/// -
/// PVD_CONFIG
/// Service Provider Dependent
///
/// This object stores the configuration information for the service provider associated with socket s. The exact format of this
/// data structure is service provider specific.
///
///
///
/// For more complete and detailed information about socket options for level = SOL_SOCKET, see SOL_SOCKET Socket Options.
/// level = IPPROTO_TCP
///
///
/// Value
/// Type
/// Description
///
/// -
/// TCP_NODELAY
/// BOOL
///
/// Disables the Nagle algorithm for send coalescing.This socket option is included for backward compatibility with Windows Sockets 1.1
///
///
///
///
/// For more complete and detailed information about socket options for level = IPPROTO_TCP, see IPPROTO_TCP Socket Options.
///
/// level = NSPROTO_IPX
///
///
/// Value
/// Type
/// Description
///
/// -
/// IPX_PTYPE
/// int
/// Sets the IPX packet type.
///
/// -
/// IPX_FILTERPTYPE
/// int
/// Sets the receive filter packet type
///
/// -
/// IPX_STOPFILTERPTYPE
/// int
/// Stops filtering the filter type set with IPX_FILTERTYPE
///
/// -
/// IPX_DSTYPE
/// int
/// Sets the value of the data stream field in the SPX header on every packet sent.
///
/// -
/// IPX_EXTENDED_ADDRESS
/// BOOL
/// Sets whether extended addressing is enabled.
///
/// -
/// IPX_RECVHDR
/// BOOL
/// Sets whether the protocol header is sent up on all receive headers.
///
/// -
/// IPX_RECEIVE_BROADCAST
/// BOOL
///
/// Indicates broadcast packets are likely on the socket. Set to TRUE by default. Applications that do not use broadcasts should set
/// this to FALSE for better system performance.
///
///
/// -
/// IPX_IMMEDIATESPXACK
/// BOOL
///
/// Directs SPX connections not to delay before sending an ACK. Applications without back-and-forth traffic should set this to TRUE
/// to increase performance.
///
///
///
///
/// For more complete and detailed information about socket options for level = NSPROTO_IPX, see NSPROTO_IPX Socket Options.
///
/// BSD options not supported for setsockopt are shown in the following table.
///
///
/// Value
/// Type
/// Description
///
/// -
/// SO_ACCEPTCONN
/// BOOL
///
/// Returns whether a socket is in listening mode. This option is only Valid for connection-oriented protocols. This socket option
/// is not supported for the setting.
///
///
/// -
/// SO_RCVLOWAT
/// int
///
/// A socket option from BSD UNIX included for backward compatibility. This option sets the minimum number of bytes to process for
/// socket input operations.
///
///
/// -
/// SO_SNDLOWAT
/// int
///
/// A socket option from BSD UNIX included for backward compatibility. This option sets the minimum number of bytes to process for
/// socket output operations.
///
///
/// -
/// SO_TYPE
/// int
///
/// Returns the socket type for the given socket (SOCK_STREAM or SOCK_DGRAM, for example This socket option is not supported for the
/// setting the socket type.
///
///
///
///
/// Note When issuing a blocking Winsock call such as setsockopt, Winsock may need to wait for a network event before
/// the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous
/// procedure call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an
/// ongoing blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Example Code
/// The following example demonstrates the setsockopt function.
/// Notes for IrDA Sockets
/// When developing applications using Windows sockets for IrDA, note the following:
///
/// -
/// The Af_irda.h header file must be explicitly included.
///
/// -
/// IrDA provides the following socket option:
///
///
///
/// The IRLMP_IAS_SET socket option enables the application to set a single attribute of a single class in the local IAS. The
/// application specifies the class to set, the attribute, and attribute type. The application is expected to allocate a buffer of
/// the necessary size for the passed parameters.
///
///
/// IrDA provides an IAS database that stores IrDA-based information. Limited access to the IAS database is available through the
/// Windows Sockets 2 interface, but such access is not normally used by applications, and exists primarily to support connections
/// to non-Windows devices that are not compliant with the Windows Sockets 2 IrDA conventions.
///
/// The following structure, IAS_SET, is used with the IRLMP_IAS_SET setsockopt option to manage the local IAS database:
/// The following structure, IAS_QUERY, is used with the IRLMP_IAS_QUERY setsockopt option to query a peer's IAS database:
/// Many SO_ level socket options are not meaningful to IrDA. Only SO_LINGER is specifically supported.
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-setsockopt int setsockopt( SOCKET s, int level, int
// optname, const char *optval, int optlen );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "3a6960c9-0c04-4403-aee1-ce250459dc30")]
public static extern int setsockopt(SOCKET s, int level, int optname, IntPtr optval, int optlen);
/// The shutdown function disables sends or receives on a socket.
/// A descriptor identifying a socket.
///
///
/// A flag that describes what types of operation will no longer be allowed. Possible values for this flag are listed in the
/// Winsock2.h header file.
///
///
///
/// Value
/// Meaning
///
/// -
/// SD_RECEIVE 0
/// Shutdown receive operations.
///
/// -
/// SD_SEND 1
/// Shutdown send operations.
///
/// -
/// SD_BOTH 2
/// Shutdown both send and receive operations.
///
///
///
///
///
/// If no error occurs, shutdown returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can
/// be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSAECONNABORTED
///
/// The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no
/// longer usable. This error applies only to a connection-oriented socket.
///
///
/// -
/// WSAECONNRESET
///
/// The virtual circuit was reset by the remote side executing a hard or abortive close. The application should close the socket as
/// it is no longer usable. This error applies only to a connection-oriented socket.
///
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEINVAL
///
/// The how parameter is not valid, or is not consistent with the socket type. For example, SD_SEND is used with a UNI_RECV socket type.
///
///
/// -
/// WSAENETDOWN
/// The network subsystem has failed.
///
/// -
/// WSAENOTCONN
/// The socket is not connected. This error applies only to a connection-oriented socket.
///
/// -
/// WSAENOTSOCK
///
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
///
///
///
/// The shutdown function is used on all types of sockets to disable reception, transmission, or both.
///
/// If the how parameter is SD_RECEIVE, subsequent calls to the recv function on the socket will be disallowed. This has no effect
/// on the lower protocol layers. For TCP sockets, if there is still data queued on the socket waiting to be received, or data
/// arrives subsequently, the connection is reset, since the data cannot be delivered to the user. For UDP sockets, incoming
/// datagrams are accepted and queued. In no case will an ICMP error packet be generated.
///
///
/// If the how parameter is SD_SEND, subsequent calls to the send function are disallowed. For TCP sockets, a FIN will be sent after
/// all data is sent and acknowledged by the receiver.
///
/// Setting how to SD_BOTH disables both sends and receives as described above.
///
/// The shutdown function does not close the socket. Any resources attached to the socket will not be freed until closesocket
/// is invoked.
///
///
/// To assure that all data is sent and received on a connected socket before it is closed, an application should use
/// shutdown to close connection before calling closesocket. One method to wait for notification that the remote end has sent
/// all its data and initiated a graceful disconnect uses the WSAEventSelect function as follows :
///
///
/// -
/// Call WSAEventSelect to register for FD_CLOSE notification.
///
/// -
/// Call shutdown with how=SD_SEND.
///
/// -
///
/// When FD_CLOSE received, call the recv or WSARecv until the function completes with success and indicates that zero bytes were
/// received. If SOCKET_ERROR is returned, then the graceful disconnect is not possible.
///
///
/// -
/// Call closesocket.
///
///
///
/// Another method to wait for notification that the remote end has sent all its data and initiated a graceful disconnect uses
/// overlapped receive calls follows :
///
///
/// -
/// Call shutdown with how=SD_SEND.
///
/// -
///
/// Call recv or WSARecv until the function completes with success and indicates zero bytes were received. If SOCKET_ERROR is
/// returned, then the graceful disconnect is not possible.
///
///
/// -
/// Call closesocket.
///
///
/// Note The shutdown function does not block regardless of the SO_LINGER setting on the socket.
/// For more information, see the section on Graceful Shutdown, Linger Options, and Socket Closure.
///
/// Once the shutdown function is called to disable send, receive, or both, there is no method to re-enable send or receive
/// for the existing socket connection.
///
///
/// An application should not rely on being able to reuse a socket after it has been shut down. In particular, a Windows Sockets
/// provider is not required to support the use of connect on a socket that has been shut down.
///
///
/// If an application wants to reuse a socket, then the DisconnectEx function should be called with the dwFlags parameter set to
/// TF_REUSE_SOCKET to close a connection on a socket and prepare the socket handle to be reused. When the
/// DisconnectEx request completes, the socket handle can be passed to the AcceptEx or ConnectEx function.
///
///
/// If an application wants to reuse a socket, the TransmitFile or TransmitPackets functions can be called with the dwFlags
/// parameter set with TF_DISCONNECT and TF_REUSE_SOCKET to disconnect after all the data has been queued for
/// transmission and prepare the socket handle to be reused. When the TransmitFile request completes, the socket handle can
/// be passed to the function call previously used to establish the connection, such as AcceptEx or ConnectEx. When the
/// TransmitPackets function completes, the socket handle can be passed to the AcceptEx function.
///
///
/// Note The socket level disconnect is subject to the behavior of the underlying transport. For example, a TCP socket may be
/// subject to the TCP TIME_WAIT state, causing the DisconnectEx, TransmitFile, or TransmitPackets call to be delayed.
///
///
/// Note When issuing a blocking Winsock call such as shutdown, Winsock may need to wait for a network event before
/// the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous
/// procedure call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an
/// ongoing blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.
///
/// Notes for ATM
///
/// There are important issues associated with connection teardown when using Asynchronous Transfer Mode (ATM) and Windows Sockets
/// 2. For more information about these important considerations, see the section titled Notes for ATM in the Remarks section of the
/// closesocket function reference.
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-shutdown int shutdown( SOCKET s, int how );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock.h", MSDNShortId = "6998f0c6-adc9-481f-b9fb-75f9c9f5caaf")]
public static extern int shutdown(SOCKET s, SD how);
/// The socket function creates a socket that is bound to a specific transport service provider.
///
/// The address family specification. Possible values for the address family are defined in the Winsock2.h header file.
///
/// On the Windows SDK released for Windows Vista and later, the organization of header files has changed and the possible values
/// for the address family are defined in the Ws2def.h header file. Note that the Ws2def.h header file is automatically included in
/// Winsock2.h, and should never be used directly.
///
///
/// The values currently supported are AF_INET or AF_INET6, which are the Internet address family formats for IPv4 and IPv6. Other
/// options for address family (AF_NETBIOS for use with NetBIOS, for example) are supported if a Windows Sockets service provider
/// for the address family is installed. Note that the values for the AF_ address family and PF_ protocol family constants are
/// identical (for example, AF_INET and PF_INET), so either constant can be used.
///
/// The table below lists common values for address family although many other values are possible.
///
///
/// Af
/// Meaning
///
/// -
/// AF_UNSPEC 0
/// The address family is unspecified.
///
/// -
/// AF_INET 2
/// The Internet Protocol version 4 (IPv4) address family.
///
/// -
/// AF_IPX 6
///
/// The IPX/SPX address family. This address family is only supported if the NWLink IPX/SPX NetBIOS Compatible Transport protocol is
/// installed. This address family is not supported on Windows Vista and later.
///
///
/// -
/// AF_APPLETALK 16
///
/// The AppleTalk address family. This address family is only supported if the AppleTalk protocol is installed. This address family
/// is not supported on Windows Vista and later.
///
///
/// -
/// AF_NETBIOS 17
///
/// The NetBIOS address family. This address family is only supported if the Windows Sockets provider for NetBIOS is installed. The
/// Windows Sockets provider for NetBIOS is supported on 32-bit versions of Windows. This provider is installed by default on 32-bit
/// versions of Windows. The Windows Sockets provider for NetBIOS is not supported on 64-bit versions of windows including Windows
/// 7, Windows Server 2008, Windows Vista, Windows Server 2003, or Windows XP. The Windows Sockets provider for NetBIOS only
/// supports sockets where the type parameter is set to SOCK_DGRAM. The Windows Sockets provider for NetBIOS is not directly related
/// to the NetBIOS programming interface. The NetBIOS programming interface is not supported on Windows Vista, Windows Server 2008,
/// and later.
///
///
/// -
/// AF_INET6 23
/// The Internet Protocol version 6 (IPv6) address family.
///
/// -
/// AF_IRDA 26
///
/// The Infrared Data Association (IrDA) address family. This address family is only supported if the computer has an infrared port
/// and driver installed.
///
///
/// -
/// AF_BTH 32
///
/// The Bluetooth address family. This address family is supported on Windows XP with SP2 or later if the computer has a Bluetooth
/// adapter and driver installed.
///
///
///
///
///
/// The type specification for the new socket.
/// Possible values for the socket type are defined in the Winsock2.h header file.
/// The following table lists the possible values for the type parameter supported for Windows Sockets 2:
///
///
/// Type
/// Meaning
///
/// -
/// SOCK_STREAM 1
///
/// A socket type that provides sequenced, reliable, two-way, connection-based byte streams with an OOB data transmission mechanism.
/// This socket type uses the Transmission Control Protocol (TCP) for the Internet address family (AF_INET or AF_INET6).
///
///
/// -
/// SOCK_DGRAM 2
///
/// A socket type that supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length.
/// This socket type uses the User Datagram Protocol (UDP) for the Internet address family (AF_INET or AF_INET6).
///
///
/// -
/// SOCK_RAW 3
///
/// A socket type that provides a raw socket that allows an application to manipulate the next upper-layer protocol header. To
/// manipulate the IPv4 header, the IP_HDRINCL socket option must be set on the socket. To manipulate the IPv6 header, the
/// IPV6_HDRINCL socket option must be set on the socket.
///
///
/// -
/// SOCK_RDM 4
///
/// A socket type that provides a reliable message datagram. An example of this type is the Pragmatic General Multicast (PGM)
/// multicast protocol implementation in Windows, often referred to as reliable multicast programming. This type value is only
/// supported if the Reliable Multicast Protocol is installed.
///
///
/// -
/// SOCK_SEQPACKET 5
/// A socket type that provides a pseudo-stream packet based on datagrams.
///
///
///
/// In Windows Sockets 2, new socket types were introduced. An application can dynamically discover the attributes of each available
/// transport protocol through the WSAEnumProtocols function. So an application can determine the possible socket type and protocol
/// options for an address family and use this information when specifying this parameter. Socket type definitions in the Winsock2.h
/// and Ws2def.h header files will be periodically updated as new socket types, address families, and protocols are defined.
///
/// In Windows Sockets 1.1, the only possible socket types are SOCK_DGRAM and SOCK_STREAM.
///
///
///
/// The protocol to be used. The possible options for the protocol parameter are specific to the address family and socket type
/// specified. Possible values for the protocol are defined in the Winsock2.h and Wsrm.h header files.
///
///
/// On the Windows SDK released for Windows Vista and later, the organization of header files has changed and this parameter can be
/// one of the values from the IPPROTO enumeration type defined in the Ws2def.h header file. Note that the Ws2def.h header
/// file is automatically included in Winsock2.h, and should never be used directly.
///
///
/// If a value of 0 is specified, the caller does not wish to specify a protocol and the service provider will choose the protocol
/// to use.
///
///
/// When the af parameter is AF_INET or AF_INET6 and the type is SOCK_RAW, the value specified for the protocol is set in the
/// protocol field of the IPv6 or IPv4 packet header.
///
/// The table below lists common values for the protocol although many other values are possible.
///
///
/// protocol
/// Meaning
///
/// -
/// IPPROTO_ICMP 1
///
/// The Internet Control Message Protocol (ICMP). This is a possible value when the af parameter is AF_UNSPEC, AF_INET, or AF_INET6
/// and the type parameter is SOCK_RAW or unspecified. This protocol value is supported on Windows XP and later.
///
///
/// -
/// IPPROTO_IGMP 2
///
/// The Internet Group Management Protocol (IGMP). This is a possible value when the af parameter is AF_UNSPEC, AF_INET, or AF_INET6
/// and the type parameter is SOCK_RAW or unspecified. This protocol value is supported on Windows XP and later.
///
///
/// -
/// BTHPROTO_RFCOMM 3
///
/// The Bluetooth Radio Frequency Communications (Bluetooth RFCOMM) protocol. This is a possible value when the af parameter is
/// AF_BTH and the type parameter is SOCK_STREAM. This protocol value is supported on Windows XP with SP2 or later.
///
///
/// -
/// IPPROTO_TCP 6
///
/// The Transmission Control Protocol (TCP). This is a possible value when the af parameter is AF_INET or AF_INET6 and the type
/// parameter is SOCK_STREAM.
///
///
/// -
/// IPPROTO_UDP 17
///
/// The User Datagram Protocol (UDP). This is a possible value when the af parameter is AF_INET or AF_INET6 and the type parameter
/// is SOCK_DGRAM.
///
///
/// -
/// IPPROTO_ICMPV6 58
///
/// The Internet Control Message Protocol Version 6 (ICMPv6). This is a possible value when the af parameter is AF_UNSPEC, AF_INET,
/// or AF_INET6 and the type parameter is SOCK_RAW or unspecified. This protocol value is supported on Windows XP and later.
///
///
/// -
/// IPPROTO_RM 113
///
/// The PGM protocol for reliable multicast. This is a possible value when the af parameter is AF_INET and the type parameter is
/// SOCK_RDM. On the Windows SDK released for Windows Vista and later, this protocol is also called IPPROTO_PGM. This protocol value
/// is only supported if the Reliable Multicast Protocol is installed.
///
///
///
///
///
///
/// If no error occurs, socket returns a descriptor referencing the new socket. Otherwise, a value of INVALID_SOCKET is
/// returned, and a specific error code can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem or the associated service provider has failed.
///
/// -
/// WSAEAFNOSUPPORT
///
/// The specified address family is not supported. For example, an application tried to create a socket for the AF_IRDA address
/// family but an infrared adapter and device driver is not installed on the local computer.
///
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEMFILE
/// No more socket descriptors are available.
///
/// -
/// WSAEINVAL
///
/// An invalid argument was supplied. This error is returned if the af parameter is set to AF_UNSPEC and the type and protocol
/// parameter are unspecified.
///
///
/// -
/// WSAEINVALIDPROVIDER
/// The service provider returned a version other than 2.2.
///
/// -
/// WSAEINVALIDPROCTABLE
/// The service provider returned an invalid or incomplete procedure table to the WSPStartup.
///
/// -
/// WSAENOBUFS
/// No buffer space is available. The socket cannot be created.
///
/// -
/// WSAEPROTONOSUPPORT
/// The specified protocol is not supported.
///
/// -
/// WSAEPROTOTYPE
/// The specified protocol is the wrong type for this socket.
///
/// -
/// WSAEPROVIDERFAILEDINIT
///
/// The service provider failed to initialize. This error is returned if a layered service provider (LSP) or namespace provider was
/// improperly installed or the provider fails to operate correctly.
///
///
/// -
/// WSAESOCKTNOSUPPORT
/// The specified socket type is not supported in this address family.
///
///
///
///
///
/// The socket function causes a socket descriptor and any related resources to be allocated and bound to a specific
/// transport-service provider. Winsock will utilize the first available service provider that supports the requested combination of
/// address family, socket type and protocol parameters. The socket that is created will have the overlapped attribute as a default.
/// For Windows, the Microsoft-specific socket option, SO_OPENTYPE, defined in Mswsock.h can affect this default. See
/// Microsoft-specific documentation for a detailed description of SO_OPENTYPE.
///
///
/// Sockets without the overlapped attribute can be created by using WSASocket. All functions that allow overlapped operation
/// (WSASend, WSARecv, WSASendTo, WSARecvFrom, and WSAIoctl) also support nonoverlapped usage on an overlapped socket if the values
/// for parameters related to overlapped operation are NULL.
///
///
/// When selecting a protocol and its supporting service provider this procedure will only choose a base protocol or a protocol
/// chain, not a protocol layer by itself. Unchained protocol layers are not considered to have partial matches on type or af
/// either. That is, they do not lead to an error code of WSAEAFNOSUPPORT or WSAEPROTONOSUPPORT if no suitable protocol is found.
///
///
/// Note The manifest constant AF_UNSPEC continues to be defined in the header file but its use is strongly
/// discouraged, as this can cause ambiguity in interpreting the value of the protocol parameter.
///
///
/// Applications are encouraged to use AF_INET6 for the af parameter and create a dual-mode socket that can be used with both
/// IPv4 and IPv6.
///
///
/// Connection-oriented sockets such as SOCK_STREAM provide full-duplex connections, and must be in a connected state before
/// any data can be sent or received on it. A connection to another socket is created with a connect call. Once connected, data can
/// be transferred using send and recv calls. When a session has been completed, a closesocket must be performed.
///
///
/// The communications protocols used to implement a reliable, connection-oriented socket ensure that data is not lost or
/// duplicated. If data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length
/// of time, the connection is considered broken and subsequent calls will fail with the error code set to WSAETIMEDOUT.
///
///
/// Connectionless, message-oriented sockets allow sending and receiving of datagrams to and from arbitrary peers using sendto and
/// recvfrom. If such a socket is connected to a specific peer, datagrams can be sent to that peer using send and can be received
/// only from this peer using recv.
///
///
/// IPv6 and IPv4 operate differently when receiving a socket with a type of SOCK_RAW. The IPv4 receive packet includes the
/// packet payload, the next upper-level header (for example, the IP header for a TCP or UDP packet), and the IPv4 packet header.
/// The IPv6 receive packet includes the packet payload and the next upper-level header. The IPv6 receive packet never includes the
/// IPv6 packet header.
///
/// Note On Windows NT, raw socket support requires administrative privileges.
///
/// A socket with a type parameter of SOCK_SEQPACKET is based on datagrams, but functions as a pseudo-stream protocol. For
/// both send and receive packets, separate datagrams are used. However, Windows Sockets can coalesce multiple receive packets into
/// a single packet. So an application can issue a receive call (for example, recv or WSARecvEx) and retrieve the data from several
/// coalesced multiple packets in single call. The AF_NETBIOS address family supports a type parameter of SOCK_SEQPACKET.
///
///
/// When the af parameter is AF_NETBIOS for NetBIOS over TCP/IP, the type parameter can be SOCK_DGRAM or
/// SOCK_SEQPACKET. For the AF_NETBIOS address family, the protocol parameter is the LAN adapter number represented as
/// a negative number.
///
///
/// On Windows XP and later, the following command can be used to list the Windows Sockets catalog to determine the service
/// providers installed and the address family, socket type, and protocols that are supported.
///
/// netsh winsock show catalog
///
/// Support for sockets with type SOCK_RAW is not required, but service providers are encouraged to support raw sockets as practicable.
///
/// Notes for IrDA Sockets
/// Keep the following in mind:
///
/// -
/// The Af_irda.h header file must be explicitly included.
///
/// -
/// Only SOCK_STREAM is supported; the SOCK_DGRAM type is not supported by IrDA.
///
/// -
/// The protocol parameter is always set to 0 for IrDA.
///
///
///
/// A socket for use with the AF_IRDA address family can only be created if the local computer has an infrared port and driver
/// installed. Otherwise, a call to the socket function with af parameter set to AF_IRDA will fail and WSAGetLastError
/// returns WSAEPROTONOSUPPORT.
///
/// Example Code
///
/// The following example demonstrates the use of the socket function to create a socket that is bound to a specific
/// transport service provider..
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-socket SOCKET WSAAPI socket( int af, int type, int
// protocol );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock2.h", MSDNShortId = "6bf6e6c4-6268-479c-86a6-52e90cf317db")]
public static extern SafeSOCKET socket(ADDRESS_FAMILY af, SOCK type, IPPROTO protocol);
/// The socket function creates a socket that is bound to a specific transport service provider.
///
/// The address family specification. Possible values for the address family are defined in the Winsock2.h header file.
///
/// On the Windows SDK released for Windows Vista and later, the organization of header files has changed and the possible values
/// for the address family are defined in the Ws2def.h header file. Note that the Ws2def.h header file is automatically included in
/// Winsock2.h, and should never be used directly.
///
///
/// The values currently supported are AF_INET or AF_INET6, which are the Internet address family formats for IPv4 and IPv6. Other
/// options for address family (AF_NETBIOS for use with NetBIOS, for example) are supported if a Windows Sockets service provider
/// for the address family is installed. Note that the values for the AF_ address family and PF_ protocol family constants are
/// identical (for example, AF_INET and PF_INET), so either constant can be used.
///
/// The table below lists common values for address family although many other values are possible.
///
///
/// Af
/// Meaning
///
/// -
/// AF_UNSPEC 0
/// The address family is unspecified.
///
/// -
/// AF_INET 2
/// The Internet Protocol version 4 (IPv4) address family.
///
/// -
/// AF_IPX 6
///
/// The IPX/SPX address family. This address family is only supported if the NWLink IPX/SPX NetBIOS Compatible Transport protocol is
/// installed. This address family is not supported on Windows Vista and later.
///
///
/// -
/// AF_APPLETALK 16
///
/// The AppleTalk address family. This address family is only supported if the AppleTalk protocol is installed. This address family
/// is not supported on Windows Vista and later.
///
///
/// -
/// AF_NETBIOS 17
///
/// The NetBIOS address family. This address family is only supported if the Windows Sockets provider for NetBIOS is installed. The
/// Windows Sockets provider for NetBIOS is supported on 32-bit versions of Windows. This provider is installed by default on 32-bit
/// versions of Windows. The Windows Sockets provider for NetBIOS is not supported on 64-bit versions of windows including Windows
/// 7, Windows Server 2008, Windows Vista, Windows Server 2003, or Windows XP. The Windows Sockets provider for NetBIOS only
/// supports sockets where the type parameter is set to SOCK_DGRAM. The Windows Sockets provider for NetBIOS is not directly related
/// to the NetBIOS programming interface. The NetBIOS programming interface is not supported on Windows Vista, Windows Server 2008,
/// and later.
///
///
/// -
/// AF_INET6 23
/// The Internet Protocol version 6 (IPv6) address family.
///
/// -
/// AF_IRDA 26
///
/// The Infrared Data Association (IrDA) address family. This address family is only supported if the computer has an infrared port
/// and driver installed.
///
///
/// -
/// AF_BTH 32
///
/// The Bluetooth address family. This address family is supported on Windows XP with SP2 or later if the computer has a Bluetooth
/// adapter and driver installed.
///
///
///
///
///
/// The type specification for the new socket.
/// Possible values for the socket type are defined in the Winsock2.h header file.
/// The following table lists the possible values for the type parameter supported for Windows Sockets 2:
///
///
/// Type
/// Meaning
///
/// -
/// SOCK_STREAM 1
///
/// A socket type that provides sequenced, reliable, two-way, connection-based byte streams with an OOB data transmission mechanism.
/// This socket type uses the Transmission Control Protocol (TCP) for the Internet address family (AF_INET or AF_INET6).
///
///
/// -
/// SOCK_DGRAM 2
///
/// A socket type that supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length.
/// This socket type uses the User Datagram Protocol (UDP) for the Internet address family (AF_INET or AF_INET6).
///
///
/// -
/// SOCK_RAW 3
///
/// A socket type that provides a raw socket that allows an application to manipulate the next upper-layer protocol header. To
/// manipulate the IPv4 header, the IP_HDRINCL socket option must be set on the socket. To manipulate the IPv6 header, the
/// IPV6_HDRINCL socket option must be set on the socket.
///
///
/// -
/// SOCK_RDM 4
///
/// A socket type that provides a reliable message datagram. An example of this type is the Pragmatic General Multicast (PGM)
/// multicast protocol implementation in Windows, often referred to as reliable multicast programming. This type value is only
/// supported if the Reliable Multicast Protocol is installed.
///
///
/// -
/// SOCK_SEQPACKET 5
/// A socket type that provides a pseudo-stream packet based on datagrams.
///
///
///
/// In Windows Sockets 2, new socket types were introduced. An application can dynamically discover the attributes of each available
/// transport protocol through the WSAEnumProtocols function. So an application can determine the possible socket type and protocol
/// options for an address family and use this information when specifying this parameter. Socket type definitions in the Winsock2.h
/// and Ws2def.h header files will be periodically updated as new socket types, address families, and protocols are defined.
///
/// In Windows Sockets 1.1, the only possible socket types are SOCK_DGRAM and SOCK_STREAM.
///
///
///
/// The protocol to be used. The possible options for the protocol parameter are specific to the address family and socket type
/// specified. Possible values for the protocol are defined in the Winsock2.h and Wsrm.h header files.
///
///
/// On the Windows SDK released for Windows Vista and later, the organization of header files has changed and this parameter can be
/// one of the values from the IPPROTO enumeration type defined in the Ws2def.h header file. Note that the Ws2def.h header
/// file is automatically included in Winsock2.h, and should never be used directly.
///
///
/// If a value of 0 is specified, the caller does not wish to specify a protocol and the service provider will choose the protocol
/// to use.
///
///
/// When the af parameter is AF_INET or AF_INET6 and the type is SOCK_RAW, the value specified for the protocol is set in the
/// protocol field of the IPv6 or IPv4 packet header.
///
/// The table below lists common values for the protocol although many other values are possible.
///
///
/// protocol
/// Meaning
///
/// -
/// IPPROTO_ICMP 1
///
/// The Internet Control Message Protocol (ICMP). This is a possible value when the af parameter is AF_UNSPEC, AF_INET, or AF_INET6
/// and the type parameter is SOCK_RAW or unspecified. This protocol value is supported on Windows XP and later.
///
///
/// -
/// IPPROTO_IGMP 2
///
/// The Internet Group Management Protocol (IGMP). This is a possible value when the af parameter is AF_UNSPEC, AF_INET, or AF_INET6
/// and the type parameter is SOCK_RAW or unspecified. This protocol value is supported on Windows XP and later.
///
///
/// -
/// BTHPROTO_RFCOMM 3
///
/// The Bluetooth Radio Frequency Communications (Bluetooth RFCOMM) protocol. This is a possible value when the af parameter is
/// AF_BTH and the type parameter is SOCK_STREAM. This protocol value is supported on Windows XP with SP2 or later.
///
///
/// -
/// IPPROTO_TCP 6
///
/// The Transmission Control Protocol (TCP). This is a possible value when the af parameter is AF_INET or AF_INET6 and the type
/// parameter is SOCK_STREAM.
///
///
/// -
/// IPPROTO_UDP 17
///
/// The User Datagram Protocol (UDP). This is a possible value when the af parameter is AF_INET or AF_INET6 and the type parameter
/// is SOCK_DGRAM.
///
///
/// -
/// IPPROTO_ICMPV6 58
///
/// The Internet Control Message Protocol Version 6 (ICMPv6). This is a possible value when the af parameter is AF_UNSPEC, AF_INET,
/// or AF_INET6 and the type parameter is SOCK_RAW or unspecified. This protocol value is supported on Windows XP and later.
///
///
/// -
/// IPPROTO_RM 113
///
/// The PGM protocol for reliable multicast. This is a possible value when the af parameter is AF_INET and the type parameter is
/// SOCK_RDM. On the Windows SDK released for Windows Vista and later, this protocol is also called IPPROTO_PGM. This protocol value
/// is only supported if the Reliable Multicast Protocol is installed.
///
///
///
///
///
///
/// If no error occurs, socket returns a descriptor referencing the new socket. Otherwise, a value of INVALID_SOCKET is
/// returned, and a specific error code can be retrieved by calling WSAGetLastError.
///
///
///
/// Error code
/// Meaning
///
/// -
/// WSANOTINITIALISED
/// A successful WSAStartup call must occur before using this function.
///
/// -
/// WSAENETDOWN
/// The network subsystem or the associated service provider has failed.
///
/// -
/// WSAEAFNOSUPPORT
///
/// The specified address family is not supported. For example, an application tried to create a socket for the AF_IRDA address
/// family but an infrared adapter and device driver is not installed on the local computer.
///
///
/// -
/// WSAEINPROGRESS
/// A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
///
/// -
/// WSAEMFILE
/// No more socket descriptors are available.
///
/// -
/// WSAEINVAL
///
/// An invalid argument was supplied. This error is returned if the af parameter is set to AF_UNSPEC and the type and protocol
/// parameter are unspecified.
///
///
/// -
/// WSAEINVALIDPROVIDER
/// The service provider returned a version other than 2.2.
///
/// -
/// WSAEINVALIDPROCTABLE
/// The service provider returned an invalid or incomplete procedure table to the WSPStartup.
///
/// -
/// WSAENOBUFS
/// No buffer space is available. The socket cannot be created.
///
/// -
/// WSAEPROTONOSUPPORT
/// The specified protocol is not supported.
///
/// -
/// WSAEPROTOTYPE
/// The specified protocol is the wrong type for this socket.
///
/// -
/// WSAEPROVIDERFAILEDINIT
///
/// The service provider failed to initialize. This error is returned if a layered service provider (LSP) or namespace provider was
/// improperly installed or the provider fails to operate correctly.
///
///
/// -
/// WSAESOCKTNOSUPPORT
/// The specified socket type is not supported in this address family.
///
///
///
///
///
/// The socket function causes a socket descriptor and any related resources to be allocated and bound to a specific
/// transport-service provider. Winsock will utilize the first available service provider that supports the requested combination of
/// address family, socket type and protocol parameters. The socket that is created will have the overlapped attribute as a default.
/// For Windows, the Microsoft-specific socket option, SO_OPENTYPE, defined in Mswsock.h can affect this default. See
/// Microsoft-specific documentation for a detailed description of SO_OPENTYPE.
///
///
/// Sockets without the overlapped attribute can be created by using WSASocket. All functions that allow overlapped operation
/// (WSASend, WSARecv, WSASendTo, WSARecvFrom, and WSAIoctl) also support nonoverlapped usage on an overlapped socket if the values
/// for parameters related to overlapped operation are NULL.
///
///
/// When selecting a protocol and its supporting service provider this procedure will only choose a base protocol or a protocol
/// chain, not a protocol layer by itself. Unchained protocol layers are not considered to have partial matches on type or af
/// either. That is, they do not lead to an error code of WSAEAFNOSUPPORT or WSAEPROTONOSUPPORT if no suitable protocol is found.
///
///
/// Note The manifest constant AF_UNSPEC continues to be defined in the header file but its use is strongly
/// discouraged, as this can cause ambiguity in interpreting the value of the protocol parameter.
///
///
/// Applications are encouraged to use AF_INET6 for the af parameter and create a dual-mode socket that can be used with both
/// IPv4 and IPv6.
///
///
/// Connection-oriented sockets such as SOCK_STREAM provide full-duplex connections, and must be in a connected state before
/// any data can be sent or received on it. A connection to another socket is created with a connect call. Once connected, data can
/// be transferred using send and recv calls. When a session has been completed, a closesocket must be performed.
///
///
/// The communications protocols used to implement a reliable, connection-oriented socket ensure that data is not lost or
/// duplicated. If data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length
/// of time, the connection is considered broken and subsequent calls will fail with the error code set to WSAETIMEDOUT.
///
///
/// Connectionless, message-oriented sockets allow sending and receiving of datagrams to and from arbitrary peers using sendto and
/// recvfrom. If such a socket is connected to a specific peer, datagrams can be sent to that peer using send and can be received
/// only from this peer using recv.
///
///
/// IPv6 and IPv4 operate differently when receiving a socket with a type of SOCK_RAW. The IPv4 receive packet includes the
/// packet payload, the next upper-level header (for example, the IP header for a TCP or UDP packet), and the IPv4 packet header.
/// The IPv6 receive packet includes the packet payload and the next upper-level header. The IPv6 receive packet never includes the
/// IPv6 packet header.
///
/// Note On Windows NT, raw socket support requires administrative privileges.
///
/// A socket with a type parameter of SOCK_SEQPACKET is based on datagrams, but functions as a pseudo-stream protocol. For
/// both send and receive packets, separate datagrams are used. However, Windows Sockets can coalesce multiple receive packets into
/// a single packet. So an application can issue a receive call (for example, recv or WSARecvEx) and retrieve the data from several
/// coalesced multiple packets in single call. The AF_NETBIOS address family supports a type parameter of SOCK_SEQPACKET.
///
///
/// When the af parameter is AF_NETBIOS for NetBIOS over TCP/IP, the type parameter can be SOCK_DGRAM or
/// SOCK_SEQPACKET. For the AF_NETBIOS address family, the protocol parameter is the LAN adapter number represented as
/// a negative number.
///
///
/// On Windows XP and later, the following command can be used to list the Windows Sockets catalog to determine the service
/// providers installed and the address family, socket type, and protocols that are supported.
///
/// netsh winsock show catalog
///
/// Support for sockets with type SOCK_RAW is not required, but service providers are encouraged to support raw sockets as practicable.
///
/// Notes for IrDA Sockets
/// Keep the following in mind:
///
/// -
/// The Af_irda.h header file must be explicitly included.
///
/// -
/// Only SOCK_STREAM is supported; the SOCK_DGRAM type is not supported by IrDA.
///
/// -
/// The protocol parameter is always set to 0 for IrDA.
///
///
///
/// A socket for use with the AF_IRDA address family can only be created if the local computer has an infrared port and driver
/// installed. Otherwise, a call to the socket function with af parameter set to AF_IRDA will fail and WSAGetLastError
/// returns WSAEPROTONOSUPPORT.
///
/// Example Code
///
/// The following example demonstrates the use of the socket function to create a socket that is bound to a specific
/// transport service provider..
///
/// Windows Phone 8: This function is supported for Windows Phone Store apps on Windows Phone 8 and later.
///
/// Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows
/// Server 2012 R2, and later.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-socket SOCKET WSAAPI socket( int af, int type, int
// protocol );
[DllImport(Lib.Ws2_32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("winsock2.h", MSDNShortId = "6bf6e6c4-6268-479c-86a6-52e90cf317db")]
public static extern SafeSOCKET socket(ADDRESS_FAMILY af, SOCK type, uint protocol);
///
/// The protoent structure contains the name and protocol numbers that correspond to a given protocol name. Applications must
/// never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is
/// allocated per thread, and therefore, the application should copy any information it needs before issuing any other Windows
/// Sockets function calls.
///
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-protoent typedef struct protoent { char *p_name; char
// **p_aliases; short p_proto; } PROTOENT, *PPROTOENT, *LPPROTOENT;
[PInvokeData("winsock.h", MSDNShortId = "8fc729dd-5a73-42a1-9c3f-adc68d83d863")]
[StructLayout(LayoutKind.Sequential)]
public struct PROTOENT
{
/// Official name of the protocol.
public StrPtrAnsi p_name;
/// Null-terminated array of alternate names.
public IntPtr p_aliases;
/// Protocol number, in host byte order.
public short p_proto;
/// Array of alternate names extracted from .
public string[] Aliases => p_aliases.ToStringEnum(p_aliases.GetNulledPtrArrayLength(), CharSet.Ansi).ToArray();
}
/// The servent structure is used to store or return the name and service number for a given service name.
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-servent typedef struct servent { char *s_name; char
// **s_aliases; #if ... char *s_proto; #if ... short s_port; #else short s_port; #endif #else char *s_proto; #endif } SERVENT,
// *PSERVENT, *LPSERVENT;
[PInvokeData("winsock.h", MSDNShortId = "8696b854-4d37-4d1b-8383-169b5dc7a2ae")]
[VanaraMarshaler(typeof(SERVENT))]
public struct SERVENT : IVanaraMarshaler
{
/// The official name of the service.
public string s_name;
/// A NULL-terminated array of alternate names.
public string[] s_aliases;
/// The port number at which the service can be contacted. Port numbers are returned in network byte order.
public short s_port;
/// The name of the protocol to use when contacting the service.
public string s_proto;
/// Use this method to address different structure layouts on 64-bit systems.
/// The ptr to convert.
/// A SERVENT structure aligned correctly.
public SERVENT FromIntPtr(IntPtr ptr)
{
if (IntPtr.Size == 8)
{
var x = ptr.ToStructure();
return new SERVENT { s_name = x.s_name, s_aliases = x.s_aliases.ToStringEnum(x.s_aliases.GetNulledPtrArrayLength(), CharSet.Ansi).ToArray(), s_port = x.s_port, s_proto = x.s_proto };
}
var s = ptr.ToStructure();
return new SERVENT { s_name = s.s_name, s_aliases = s.s_aliases.ToStringEnum(s.s_aliases.GetNulledPtrArrayLength(), CharSet.Ansi).ToArray(), s_port = s.s_port, s_proto = s.s_proto };
}
SizeT IVanaraMarshaler.GetNativeSize() => IntPtr.Size == 8 ? Marshal.SizeOf(typeof(SERVENTx64)) : Marshal.SizeOf(typeof(SERVENT));
SafeAllocatedMemoryHandle IVanaraMarshaler.MarshalManagedToNative(object managedObject)
{
if (managedObject is SERVENT s)
{
var mem = new SafeHGlobalHandle(64);
using (var str = new NativeMemoryStream(mem, 64L))
{
str.WriteReference(s.s_name);
str.WriteReferenceObject(s.s_aliases);
if (IntPtr.Size == 8)
{
str.WriteReference(s.s_proto);
str.Write((int)s.s_port);
}
else
{
str.WriteReference(s.s_proto);
str.Write((int)s.s_port);
}
}
return mem;
}
throw new ArgumentException("Object must be of type SERVENT.", nameof(managedObject));
}
object IVanaraMarshaler.MarshalNativeToManaged(IntPtr pNativeData, SizeT allocatedBytes) => FromIntPtr(pNativeData);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct SERVENTx32
{
public StrPtrAnsi s_name;
public IntPtr s_aliases;
public short s_port;
public StrPtrAnsi s_proto;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct SERVENTx64
{
public StrPtrAnsi s_name;
public IntPtr s_aliases;
public StrPtrAnsi s_proto;
public short s_port;
}
}
}
}