ioctlsocket()

The ioctlsocket() function manipulates the underlying network device associated with a socket.

Syntax


int ioctlsocket(
    SOCKET s,
    u_long cmd,
    u_long *argp
);
            

Parameters

Parameter Description
s A descriptor identifying a socket.
cmd The command for the operation. This can be one of the predefined IOCTL codes defined in Winsock. Common commands include:
  • FIONBIO: Enable or disable non-blocking mode for the socket.
  • FIONREAD: Get the number of bytes of unread data on the socket.
  • SIOCGIFADDR: Get the IP address of an interface.
  • SIOCSPPPDYNAMIC: Set the IP address for a PPP connection dynamically.
argp A pointer to the argument for the command specified by cmd. The type and meaning of argp depend on the value of cmd.

Return Value

If ioctlsocket() succeeds, the return value is zero, and the content of the buffer pointed to by argp is updated if the command requires it.

If ioctlsocket() fails, the return value is SOCKET_ERROR. To get extended error information, call WSAGetLastError().

Remarks

The ioctlsocket() function is used to perform a variety of control operations on sockets that are not directly related to sending or receiving data. These operations can include setting socket options, retrieving socket information, or manipulating socket behavior.

The specific commands supported and their associated argument structures are defined by the Winsock implementation and the underlying network protocols.

Example: Disabling Blocking Mode

The following example shows how to disable blocking mode on a socket:


#include <winsock2.h>

// Assume 'mySocket' is a valid SOCKET descriptor

unsigned long nonBlockingMode = 1; // 1 to enable non-blocking, 0 to disable

if (ioctlsocket(mySocket, FIONBIO, &nonBlockingMode) == SOCKET_ERROR) {
    // Handle error, call WSAGetLastError()
    int error = WSAGetLastError();
    // ...
} else {
    // Non-blocking mode is now enabled
}
            

Example: Getting Number of Bytes Available

This example demonstrates retrieving the number of bytes of unread data on a socket:


#include <winsock2.h>

// Assume 'mySocket' is a valid SOCKET descriptor

u_long bytesAvailable;

if (ioctlsocket(mySocket, FIONREAD, &bytesAvailable) == SOCKET_ERROR) {
    // Handle error, call WSAGetLastError()
    int error = WSAGetLastError();
    // ...
} else {
    // 'bytesAvailable' now contains the number of bytes ready to be read
    // printf("Bytes available: %lu\n", bytesAvailable);
}
            
Note: The set of available IOCTL commands can vary depending on the Winsock version and the underlying network interface. Always consult the official Winsock documentation for the specific commands and their usage.
Important: When using ioctlsocket() with commands that modify socket behavior (like FIONBIO), ensure that the application logic is prepared to handle the consequences of such changes, especially in non-blocking scenarios.

See Also