Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket communcation between C and Python

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:
like image 941
Patrick Avatar asked Feb 18 '23 14:02

Patrick


1 Answers

You are trying to write to listening socket

write(socket_fd, buffer, strlen(buffer));

You should try

write(connection_fd, buffer, strlen(buffer));
like image 100
codewarrior Avatar answered Feb 21 '23 03:02

codewarrior