andersch.dev

<2023-04-10 Mon>
[ os ]

Network socket

Sockets in networking serve as endpoints for the sending and receiving of data.

A simple socket connection between two programs

Listening socket in a python program. Start with python server.py.

#!/bin/python

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 4200));
server.listen(1)

conn, addr = server.accept(); # NOTE: accept() blocks execution

while True:
    data = conn.recv(1024);
    if (data != b''):
        print(str(data, 'ascii'));
        while (conn.sendall(b"WORLD") != None):
            pass

C program that connects to the python socket and sends a message.

#include <stdio.h>
#include <string.h>     // for strlen

#include <sys/socket.h>
#include <netinet/in.h> // for IPPROTO_IP
#include <arpa/inet.h>  // for inet_addr

// see https://www.binarytides.com/socket-programming-c-linux-tutorial/

int main(int argc, char** argv)
{
    // AF_INET: Adress Family IPv4
    // SOCK_STREAM: connection-oriented TCP
    // SOCK_DGRAM: UDP
    // 0 or IPPROTO_IP: Internet Protocol
    int socket_desc = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);

    if (socket_desc == -1)
    {
        printf("Could not create socket\n");
        return -1;
    }

    struct sockaddr_in server;

    //server.sin_addr.s_addr = inet_addr("142.250.184.238"); // google
    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons(4200);

    // Connect to remote server
    if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        printf("Connection Error\n");
        return -2;
    }

    printf("Connected\n");

    // Send some data
    //message = "GET / HTTP/1.1\r\n\r\n";
    char* message = "HELLO";
    if (send(socket_desc , message , strlen(message) , 0) < 0)
    {
        printf("Send failed\n");
        return 1;
    }
    printf("Data Send\n");

    char buffer[1024];
    int buf_len = recv(socket_desc, buffer, 1024, 0);
    if (buf_len < 0)
    {
        printf("Data recv failed\n");
    }

    buffer[buf_len] = '\0';
    printf("%s\n", buffer);

    return 0;
}