1 | initial version |
The sys/socket.h library is specific to Unix-like operating systems and is not available in a native Windows environment. However, the Windows equivalent library is Winsock (Windows Sockets). To use Winsock, you can include the header files <winsock2.h> and <ws2tcpip.h> in your program and link to the Winsock library. Here are the necessary steps:
#include <winsock2.h>
#include <ws2tcpip.h>
WSADATA wsaData;
int startupResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (startupResult != 0) {
// Handle initialization error
}
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == INVALID_SOCKET) {
// Handle socket creation error
}
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
inet_pton(AF_INET, SERVER_IP, &serverAddr.sin_addr);
int connectResult = connect(sockfd, (sockaddr*)&serverAddr, sizeof(serverAddr));
if (connectResult == SOCKET_ERROR) {
// Handle connection error
}
char buf[1024];
int receivedBytes = recv(sockfd, buf, sizeof(buf), 0);
if (receivedBytes == SOCKET_ERROR) {
// Handle receive error
}
WSACleanup();
Note that Winsock supports most of the functionalities in sys/socket.h, but there might be some differences in the functions and data structures. Therefore, it's important to refer to the Winsock documentation for specific syntax and usage.