WSASocket函数怎么使用
时间: 2024-06-10 09:07:00 浏览: 177
WSASocket函数是Windows Sockets API的一部分,用于创建一个套接字。它的使用方法和参数可以参考Microsoft的文档介绍,具体如下:
```c++
WSADATA wsaData;
SOCKET sock = INVALID_SOCKET;
addrinfo hints = { 0 };
addrinfo *result = NULL;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
iResult = getaddrinfo("www.example.com", "80", &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
sock = WSASocket(result->ai_family, result->ai_socktype, result->ai_protocol, NULL, 0, 0);
if (sock == INVALID_SOCKET) {
printf("WSASocket failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// use the socket ...
closesocket(sock);
freeaddrinfo(result);
WSACleanup();
```
注意,这里的代码仅供参考,具体情况需要根据实际需求来修改。
阅读全文