'C++ client not receiving any data from Python server

I'm working on a project with a C++ client and a Python server.

int connecting(SOCKET s){
    WSADATA wsa;
    struct sockaddr_in server;
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        std::cout<<"WSA error";
        return 1;
    }
    if((s=socket(AF_INET, SOCK_STREAM, 0))==INVALID_SOCKET){
        std::cout<<"invalid socket";
        return 1;
    }
    server.sin_addr.s_addr = inet_addr("192.168.1.10");
    server.sin_family = AF_INET;
    server.sin_port = htons(2424);

    if(connect(s , (struct sockaddr *)&server , sizeof(server))!=0){
        std::cout<<"error connecting";
        return 1;
    }
    else{
        return 0;
    }
}

void recv_data(SOCKET socket){
    char buf[buflen];
    recv(socket, buf, buflen, 0);
    std::cout<<buf;
}

int main(int argc, char* argv[]){
   SOCKET s;
   connecting(s);
   recv_data(s);
}

Here's the very basic Python server.

import socket
import struct

s=socket.socket()
s.bind(("192.168.1.10", 2424))
s.listen(1)
c, a=s.accept()
print(f"{a}")
data="Hi from server"
c.send(data.encode())

After establishing the connection in the server, the a variable is printed. Nothing is received nor printed in the client-side. I tried putting in a loop the recv() function in the client but it does not work.



Solution 1:[1]

You misunderstood argument passing by value...

void f(int x) {
    x = 5;
}

int main() {
    int j = 7;
    f(j);
    printf("%d\n", j);
}

What is j? NOT 5! The number 7 was passed into f, where it was stored in the variable x, and then the number 5 was stored in the variable x, which is not the variable j, so j was not changed.

You have this in your program:

int main(int argc, char* argv[]){
   SOCKET s;
   connecting(s);
   recv_data(s);
}

After the call connecting(s) what is s? NOT A SOCKET! Only the variable s inside the function connecting held a socket handle, and the variable s in main is not that variable, so it never got to hold a socket handle. You pass some uninitialized value to recv_data.

The function recv probably reads this random uninitialized value and returns an error code meaning "hey, that isn't a socket handle" but since your code never checked whether it returned an error code, you wouldn't know about this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user253751