简体   繁体   中英

How to send data from python to C using sockets (unix)

I'm trying to create a unix socket to allow some of my c code to talk to some of my python code. The C code is acting as the socket and the python as the client. So far I have been able to create the socket and connect the client to it, but i'm either unable to send data through it or receive data through it in either direction (I can't tell where the problem is).

I've tried changing the encoding of the data i'm sending, I've tried sending the data over and over again in case it's a timing issue, these don't appear to be the problem.

C server code:

int makeSocket(struct sockaddr_un * addr, char* path){

  unlink(path);

  int sock;
  //struct sockaddr_un addr;
  sock = socket(AF_UNIX, SOCK_STREAM, 0);
  fcntl(sock, F_SETFL, O_NONBLOCK);
  addr->sun_family = AF_UNIX;
  strncpy(addr->sun_path, path, sizeof(addr->sun_path));
  size_t size = (offsetof(struct sockaddr_un, sun_path) + strlen(addr->sun_path));
  if (bind(sock, (struct sockaddr*) addr, size) < 0){
    printf("failed to bind\n");
  }
  listen(sock, 5);
  return sock;
}

//this isn't actually here but just so you can see it being created, its a global int
globSock = makeSocket("socket.soc");

Then in an idle callback:

f (!connected){
    int len = sizeof(addr);
    if (connection = accept(globSock, (struct sockaddr*) &addr, &len) < 0){
      printf("Can't listen\n");
    } else {
      printf("connected\n");
      send(connection, "HI", strlen("HI"), 0);
      connected = 1;
    }
  } else {
    int rc;
    if (!recevd && ((rc = recv(connection,buffer,BUFFERSIZE,0)) < 0)){
      printf("nope %s\n", buffer);
    } else if (rc == 0) {
      connected = 0;
      printf("%s\n", buffer);
    } else {
      recevd = 1;
      printf("%s\n", buffer);
    }
  }

connected and recevd are flag variables and buffer is an array of char (buffer size is 100, just a #define)

Python client:

# -*- coding: utf-8 -*-
import socket
import os

print("Connecting...")
if os.path.exists("socket.soc"):
    client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    client.connect("socket.soc")
    print("Ready.")
    print("Ctrl-C to quit.")
    print("Sending 'DONE' shuts down the server and quits.")
    while True:
        try:
            x = input("> ")
            if "" != x:
                print("SEND:", x)
                client.send(x.encode('utf-8'))
                if "DONE" == x:
                    print("Shutting down.")
                    break
        except KeyboardInterrupt as k:
            print("Shutting down.")
            client.close()
            break
else:
    print("Couldn't Connect!")
    print("Done")

On the C side it repeatedly prints "nope" (the I haven't received anything yet print) and on the python side it simply asks for input, you can give it the message, it'll 'send' it and then ask for another etc...

The issue was in

if (connection = accept(globSock, (struct sockaddr*) &addr, &len) < 0){

it was saving the comparison in connection rather than the actual socket the solution was:

if ((connection = accept(globSock, (struct sockaddr*) &addr, &len)) < 0){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM