Socket communication by C language and Python

C

This is a sample program for socket communication in C language. Here, for the experiment, I am trying to connect from the client to the loopback address 127.0.0.1 so that I can do it on one computer. I referred to a website, but I forgot where it is, so I can't mention it, This is a beginner's memorandum.

Source code

sserver

sserver.c


#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
 
int main() {
    int sockfd;
    int client_sockfd;
    struct sockaddr_in addr;
 
    socklen_t len = sizeof( struct sockaddr_in );
    struct sockaddr_in from_addr;
 
    char buf[1024];
 
    //Receive buffer initialization
    memset( buf, 0, sizeof( buf ) );
 
    //Socket generation
    if( ( sockfd = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 ) {
        perror( "socket" );
    }
 
    //Stand-by IP / port number setting
    addr.sin_family = AF_INET;
    addr.sin_port = htons( 1234 );
    addr.sin_addr.s_addr = INADDR_ANY;
 
    //bind
    if( bind( sockfd, (struct sockaddr *)&addr, sizeof( addr ) ) < 0 ) {
        perror( "bind" );
    }
 
    printf("waiting for client's connection..\n");
    //Waiting for reception
    if( listen( sockfd, SOMAXCONN ) < 0 ) {
        perror( "listen" );
    }
 
    //Waiting for a connect request from a client
    if( ( client_sockfd = accept( sockfd, (struct sockaddr *)&from_addr, &len ) ) < 0 ) {
        perror( "accept" );
    }
 
    //Receive
    int rsize;
    while( 1 ) {
        rsize = recv( client_sockfd, buf, sizeof( buf ), 0 );
 
        if ( rsize == 0 ) {
            break;
        } else if ( rsize == -1 ) {
            perror( "recv" );
        } else {
            printf( "receive:%s\n", buf );
            sleep( 1 );
 
            //response
            printf( "send:%s\n", buf );
            write( client_sockfd, buf, rsize );
        }
    }
 
    //Socket closed
    close( client_sockfd );
    close( sockfd );
 
    return 0;
}

sclient

sclient.c


#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
 
int main() {
    int sockfd;
    struct sockaddr_in addr;
 
    //Socket generation
    if( (sockfd = socket( AF_INET, SOCK_STREAM, 0) ) < 0 ) {
        perror( "socket" );
    }
 
    //Destination address / port number setting
    addr.sin_family = AF_INET;
    addr.sin_port = htons( 1234 );
    addr.sin_addr.s_addr = inet_addr( "127.0.0.1" );
 
    //Server connection
    connect( sockfd, (struct sockaddr *)&addr, sizeof( struct sockaddr_in ) );
 
    //Data transmission
    char send_str[10];
    char receive_str[10];
    for ( int i = 0; i < 8; i++ ){
        sprintf( send_str, "%d", i );
        printf( "send:%d\n", i );
        if( send( sockfd, send_str, 10, 0 ) < 0 ) {
            perror( "send" );
        } else {
            recv( sockfd, receive_str, 10, 0 );
            printf( "receive:%s\n", receive_str );
        }
        sleep( 1 );
    }
 
    //Socket closed
    close( sockfd );
 
    return 0;
}

compile

Compile with cc sserver.c -o ss for the server and cc sclient.c -o sc for the client.

Experiment

First, launch sserver. Then launch sclient from another terminal. Then, 8 data will be sent from sclient, the data will be displayed, and the process will end.

Experiment result server side

$ ./ss
waiting for client's connection..
receive:0
send:0
receive:1
send:1
receive:2
send:2
receive:3
send:3
receive:4
send:4
receive:5
send:5
receive:6
send:6
receive:7
send:7

Experimental results Client side

$ ./sc
send:0
receive:0
send:1
receive:1
send:2
receive:2
send:3
receive:3
send:4
receive:4
send:5
receive:5
send:6
receive:6
send:7
receive:7

Python3

I also wrote it in Python. This works the same as the C version. Compared to C, you can write much more clearly. Reference Qiita: [Communication processing by Python] Encode to binary with .encode () and decode to string with .decode (). When encoding utf-8, use .encode ('utf-8').

sserver.py


#!/usr/bin/python3
import socket

host = "127.0.0.1"
port = 1234

serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversock.bind((host,port)) #Bind by specifying IP and PORT
serversock.listen(10) #Listen for a connection (specify the maximum number of queues)

print('Waiting for connections...')
clientsock, client_address = serversock.accept() #Store data when connected

for i in range ( 8 ):
    rcvmsg = clientsock.recv(1024).decode()
    print('Received : %s' % (rcvmsg))
    s_msg = str(i)
    print('Send : %s' % s_msg)
    clientsock.sendall(s_msg.encode())
clientsock.close()

sclient.py


#!/usr/bin/python3
import socket

host = "127.0.0.1"
port = 1234

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create an object

client.connect((host, port)) #Now connect to the server

for i in range(8):
  message = str(i)
  print('Send : %s' % message)
  client.send(message.encode()) #Send data
  response = client.recv(4096) #Receive should be a power of 2 (not too large)
  print('Received: %s' % response.decode())

Recommended Posts

Socket communication by C language and Python
Socket communication and multi-thread processing by Python
Socket communication with Python
Communication processing by Python
Python started by C programmers
Socket communication with Python LEGO Mindstorms
Function pointer and objdump ~ C language ~
Introduction to Protobuf-c (C language ⇔ Python)
100 Language Processing Knock Chapter 1 by Python
Call c language from python (python.h)
Closure 4 language comparison (Python, JavaScript, Java, C ++)
Implement FIR filters in Python and C
Socket communication using socketserver with python now
Generate C language from S-expressions in Python
RaspberryPi L Chika with Python and C #
Exchange encrypted data between Python and C #
I tried to communicate with a remote server by Socket communication with Python.
C language to see and remember Part 1 Call C language from Python (hello world)
AtCoder ABC172 C Cumulative Sum Binary Search Solved by Ruby and Python
C language to see and remember Part 4 Call C language from Python (argument) double
C language to see and remember Part 5 Call C language from Python (argument) Array
How to generate permutations in Python and C ++
62-decimal <-> decimal conversion scripts by language (R, Python, Java)
C language development / analysis tool learned by example
Communication and networking
Writing logs to CSV file (Python, C language)
python C ++ notes
python, openFrameworks (c ++)
I made a module in C language to filter images loaded by Python
Notify error and execution completion by LINE [Python]
C language to see and remember Part 3 Call C language from Python (argument) c = a + b
Python Socket communication sample / simple data throwing tool
Split Python images and arrange them side by side
Python> Sort by number and sort by alphabet> Use sorted ()
[Language processing 100 knocks 2020] Summary of answer examples by Python
Try to make a Python module in C language
Benchmark for C, Java and Python with prime factorization
Receives and outputs standard output of Python 2 and Python 3> C implementations
Control other programs from Python (communication between Python and exe)
Python learning memo for machine learning by Chainer Chapters 1 and 2
Communication between uWSGI and Nginx using Unix Domain Socket
Send data from Python to Processing via socket communication
The VIF calculated by Python and the VIF calculated by Excel are different .. ??
Interprocess communication between Ruby and Python (POSIX message queue)
Memo of "Cython-Speeding up Python by fusing with C"
HTTP server and HTTP client using Socket (+ web browser) --Python3
Go language to see and remember Part 7 C language in GO language
Serial communication with Python
[python] Compress and decompress
Primality test by Python
Serial communication with python
Python: Natural language processing
Visualization memo by Python
Python C / C ++ Extension Pattern-Pointer
Batch design and python
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
C language ALDS1_3_B Queue
Ruby, Python and map
Introduction to Python language