Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
2.3 kB
6
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #pragma comment(lib, "Ws2_32.lib")
#else
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <unistd.h>
#endif

#define DEFAULT_PORT 27015
#define DEFAULT_BUFLEN 512

int main() {
    #ifdef _WIN32
        WSADATA wsaData;
        SOCKET ConnectSocket = INVALID_SOCKET;
    #else
        int ConnectSocket;
    #endif

    struct sockaddr_in serverAddr;
    char buffer[DEFAULT_BUFLEN];
    int result;

    #ifdef _WIN32
        // Initialize Winsock
        if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
            printf("WSAStartup failed.\n");
            return 1;
        }
    #endif

    // Create a socket
    #ifdef _WIN32
        ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("Socket creation failed.\n");
            WSACleanup();
            return 1;
        }
    #else
        ConnectSocket = socket(AF_INET, SOCK_STREAM, 0);
        if (ConnectSocket < 0) {
            perror("Socket creation failed");
            return 1;
        }
    #endif

    // Setup the server address
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serverAddr.sin_port = htons(DEFAULT_PORT);

    // Connect to server
    result = connect(ConnectSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
    if (result < 0) {
        perror("Connect failed");
        #ifdef _WIN32
            closesocket(ConnectSocket);
            WSACleanup();
        #else
            close(ConnectSocket);
        #endif
        return 1;
    }

    // Send and receive data
    snprintf(buffer, sizeof(buffer), "Hello from client!");
    send(ConnectSocket, buffer, strlen(buffer), 0);
    memset(buffer, 0, sizeof(buffer));
    recv(ConnectSocket, buffer, sizeof(buffer) - 1, 0);
    printf("Received: %s\n", buffer);

    // Cleanup
    #ifdef _WIN32
        closesocket(ConnectSocket);
        WSACleanup();
    #else
        close(ConnectSocket);
    #endif

    return 0;
}
Leave a Comment