Send and receive messages in c and python (client and server)

1

I need to know how I can send and receive messages from these two different languages. I would thank that very much. (I'm new to this): $

Server python (Centos):

import socket
import threading

def conexiones(socket_cliente):
    peticion = socket_cliente.recv(1024)
    print ("[*] Mensaje recibido: %s" % peticion)
    socket_cliente.send("HOLA CLIENTE")
    socket_cliente.close()


ip = "192.168.1.101" 
puerto = 8888
max_conexiones = 5 
servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


servidor.bind((ip, puerto))
servidor.listen(max_conexiones)


print ("[*] Esperando conexiones en %s:%d" % (ip, puerto))


while True:
    cliente, direccion = servidor.accept()
    print ("[*] Conexion establecida con %s:%d" % (direccion[0] , direccion[1]))
    conexiones = threading.Thread(target=conexiones, args=(cliente,))
    conexiones.start()

Client C (windows)

#include<stdio.h>
#include<winsock2.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define PORT 8888

int main(int argc , char *argv[])
{
    WSADATA wsa;
    SOCKET s;
    struct sockaddr_in server;
    char *message , server_reply[2000];
    int recv_size;

    printf("\nInicializando WinSock");
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        printf("Failed. Error Code : %d",WSAGetLastError());
        return 1;
    }

    printf("\nINICIALIZADO.\n");

    if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
    {
        printf("No fue posible crear socket : %d" , WSAGetLastError());
    }

    printf("Socket creado.\n");


    server.sin_addr.s_addr = inet_addr("192.168.1.101");
    server.sin_family = AF_INET;
    server.sin_port = htons( PORT );

    if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        puts("Error de conexión.");
        return 1;
    }

    puts("Conectado\n");

    if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR)
    {
        puts("recv falla");
    }

    puts("Respuesta recibida\n");

    server_reply[recv_size] = '
import socket
import threading

def conexiones(socket_cliente):
    peticion = socket_cliente.recv(1024)
    print ("[*] Mensaje recibido: %s" % peticion)
    socket_cliente.send("HOLA CLIENTE")
    socket_cliente.close()


ip = "192.168.1.101" 
puerto = 8888
max_conexiones = 5 
servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


servidor.bind((ip, puerto))
servidor.listen(max_conexiones)


print ("[*] Esperando conexiones en %s:%d" % (ip, puerto))


while True:
    cliente, direccion = servidor.accept()
    print ("[*] Conexion establecida con %s:%d" % (direccion[0] , direccion[1]))
    conexiones = threading.Thread(target=conexiones, args=(cliente,))
    conexiones.start()
'; puts(server_reply); return 0; }

Beforehand, thank you very much.

    
asked by felipe 12.06.2018 в 05:36
source

1 answer

0

The code is correct except for one detail. Your python server, after accepting the connection, is waiting for some message from the client (in the first line of the function conexiones() ). On the other hand, your client C does not send anything to him, but after connecting, he waits for the server to respond. So, both are waiting, each one to send the other.

You can have the client send something with the send() function, and then everything works perfectly. For example:

[....] 
puts("Conectado\n");

if (send(s, "Hola", 4, 0) == SOCKET_ERROR )
{
    puts("send falla");
    return 1;
}

Another detail, if the server is going to execute it with Python3, you will have to convert the character strings into byte strings. For example, in the send that you make from python the message "HOLA CLIENTE" is a string of characters. In this case, it consists of only ASCII characters, you can convert it to bytes by putting a b in front of the string, like this:

socket_cliente.send(b"HOLA CLIENTE")

but in a more general case that may contain non-ascii characters, you must choose an encoding, a very common one today is UTF-8, and you would convert it like this:

socket_cliente.send("HOLA CLIENTE".encode("utf8"))

However, since your client is Windows, it might be more convenient to code it in "cp1252" , otherwise the characters could be displayed incorrectly when printed by the windows console.

On the other hand, on the server, I would not put the IP "192.168.1.101" , even if that is really the IP of the machine where the python script runs, but it would put in its place "0.0.0.0" , which represents " whatever the IP of this machine. " This gives you more flexibility if the IP of the machine changes (and it looks like it could be like that, since the IP that you had is the typical one that a DHCP server gives you).

On the client side, there, yes, you have no choice but to use the real IP that the server has. If it changes, you will have to change the code of the client, or better yet, make the IP (and why not, also the port) be received by line of arguments.

Note :

Also note that the IP that samples belong to the type of addresses called "private", which are addresses that do not go through the routers. Therefore client and server must be in the same subnet. If you need the server to be behind a NAT router (as it seems to be your case), while the client must be away, things get complicated and you should resend ports on the router and connect the client with the public IP of the router. router and the redirected port, instead of connecting directly to the machine where python is. If this is the case and you do not know how to do it, edit the question.

    
answered by 12.06.2018 / 09:22
source