ioctlsocket

ioctlsocket controls the mode of the socket. It can be used to enable or disable non‑blocking mode, retrieve the number of bytes pending in the receive buffer, and more.

Syntax

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

Parameters

NameDescription
sDescriptor identifying the socket.
cmdControl operation to perform. Common values:
  • FIONBIO: Enable/disable non‑blocking mode.
  • FIONREAD: Return number of bytes pending.
argpPointer to a variable that holds the argument or receives the result, depending on cmd.

Return Value

Returns 0 on success. On failure, returns -1 and sets WSAGetLastError() to indicate the error.

Remarks

Example

C
C++
#include <winsock2.h>
#include <stdio.h>

int main() {
    WSADATA wsa;
    SOCKET s;
    u_long mode = 1; // non‑blocking

    WSAStartup(MAKEWORD(2,2), &wsa);
    s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == INVALID_SOCKET) return 1;

    // enable non‑blocking mode
    if (ioctlsocket(s, FIONBIO, &mode) != 0) {
        printf("ioctlsocket failed: %d\n", WSAGetLastError());
        return 1;
    }

    // ... use the socket ...

    closesocket(s);
    WSACleanup();
    return 0;
}
#include <winsock2.h>
#include <iostream>

int main() {
    WSADATA wsa;
    SOCKET s;
    u_long mode = 1; // non‑blocking

    if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) {
        std::cerr << "WSAStartup failed\n";
        return 1;
    }

    s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == INVALID_SOCKET) {
        std::cerr << "socket failed: " << WSAGetLastError() << '\n';
        return 1;
    }

    // enable non‑blocking mode
    if (ioctlsocket(s, FIONBIO, &mode) != 0) {
        std::cerr << "ioctlsocket failed: " << WSAGetLastError() << '\n';
        return 1;
    }

    // ... socket operations ...

    closesocket(s);
    WSACleanup();
    return 0;
}

See Also