I just tried a really simple example to get started with sockets to communicate between a C app and Python. Here is the very simple Python script:
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/tmp/demo_socket")
print "Sending..."
s.send("Hello C from Python!")
data = s.recv(1024)
s.close()
print 'Received', repr(data)
And here the corresponding C code, without the headers:
int main(void)
{
struct sockaddr_un address;
int socket_fd, connection_fd;
socklen_t address_length;
pid_t child;
char buffer[256];
int n;
socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (socket_fd < 0){
printf("socket() failed\n");
return 1;
}
unlink("/tmp/demo_socket");
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path, UNIX_PATH_MAX, "/tmp/demo_socket");
if (bind(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0) {
printf("bind() failed\n");
return 1;
}
if(listen(socket_fd, 5) != 0) {
printf("listen() failed\n");
return 1;
}
address_length = sizeof(address);
while((connection_fd = accept(socket_fd,
(struct sockaddr *) &address,
&address_length)) > -1)
{
printf("successfully received data\n");
bzero(buffer,256);
n = read(connection_fd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n\n", buffer);
strcpy(buffer, "Hi back from the C world");
n = write(connection_fd, buffer, strlen(buffer));
if (n < 0)
printf("ERROR writing to socket\n");
break;
}
close(socket_fd);
close(socket_fd);
return(0);
}
The output is then as follows when running them in parallel:
Successfully received data
Here is the message: Hello C from Python!
ERROR writing to socket
close failed in file object destructor:
Error in sys.excepthook:
Original exception was:
So the good news is, receiving stuff from the Python world works fine, but I get an error when trying to write something back, plus it seems I get an exception in the end. Anyone an idea what I am doing wrong here?
EDIT: Thanks guys, I did the correction that you suggested, the message exchange works fine, just the C-application is still causing trouble and I am not sure why...
close failed in file object destructor:
Error in sys.excepthook:
Original exception was:
You are trying to write to listening socket
write(socket_fd, buffer, strlen(buffer));
You should try
write(connection_fd, buffer, strlen(buffer));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With