I am trying to send some data to a remote Raspberry Pi over TCP socket from a GUI that I designed with Python. I’ve implemented some basic codes. The problem is it does not give any error on Python side and Raspberry Pi side but somehow data never reaches on Raspberry Pi side.
Here is part of my Python code which is working on the PC.
self.sendsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sendsocket.connect((TCP_IP, TCP_PORT)) self.sendsocket.send("Hello world!") self.sendsocket.close()
and this is C code working on Raspberry Pi
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> void error(const char *msg) { perror(msg); exit(1); } int main(void) { int sockfd, portno; socklen_t clilen; char buffer[1024]; struct sockaddr_in serv_addr, cli_addr; int n; portno = 5005; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); listen(sockfd,5); bzero(buffer,1024); n = read(newsockfd,buffer,1024); if (n < 0) error("ERROR reading from socket"); close(sockfd); return 0; }
Advertisement
Answer
On your Ras-pi side, you are reading from newsockfd
but you are neither declaring it nor, initializing it. Also, you are just listen
-ing to the socket, but never accept
-ing a connection.
You need to add this –
socklen_t length = 0; int newsockfd = accept(socket, NULL, &length);
before your call to read
.
Also, as mentioned by @sjsam
in the comments, you need to close the socket after you are done reading using –
close(newsockfd); close(socket);
It would also be good to refactor the code and move the connection handling to a separate function (or a thread), so that your server can accept more connection. But if this is just a MCVE, that is alright.