TCP Socket

 avatar
tuhuuduc
c_cpp
25 days ago
1.7 kB
4
Indexable
Never
// Server.cpp
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int main() {
    // Create socket
    int serverSocket = socket(AF_INET, SOCK_STREAM, 0);

    // Bind socket to port
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(12345); // Port number
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    bind(serverSocket, (sockaddr*)&serverAddr, sizeof(serverAddr));

    // Listen
    listen(serverSocket, SOMAXCONN);

    // Accept incoming connections
    sockaddr_in clientAddr;
    socklen_t clientAddrSize = sizeof(clientAddr);
    int clientSocket;
    while ((clientSocket = accept(serverSocket, (sockaddr*)&clientAddr, &clientAddrSize))) {
        // Handle communication with client (in a separate thread or process)
        // For simplicity, just close the connection immediately
        close(clientSocket);
    }

    // Close server socket
    close(serverSocket);
    return 0;
}
// Client.cpp
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int main() {
    // Create socket
    int clientSocket = socket(AF_INET, SOCK_STREAM, 0);

    // Connect to server
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(12345); // Server port number
    inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr); // Server IP address
    connect(clientSocket, (sockaddr*)&serverAddr, sizeof(serverAddr));

    // Send/receive data with server (omitted for simplicity)

    // Close client socket
    close(clientSocket);
    return 0;
}
Leave a Comment