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
Name | Description |
---|---|
s | Descriptor identifying the socket. |
cmd | Control operation to perform. Common values:
|
argp | Pointer 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
- When
cmd
isFIONBIO
,*argp
is non‑zero to enable non‑blocking mode, zero to disable. - When
cmd
isFIONREAD
,*argp
receives the number of bytes that can be read without blocking. - Use
WSAGetLastError()
to retrieve error codes such asWSAEINVAL
,WSAENOTSOCK
, etc. - The function is thread‑safe.
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;
}