11

I have Android application, which needs to establish unix domain socket connection with our C++ library (using Android NDK)

public static String SOCKET_ADDRESS = "your.local.socket.address"; // STRING

There is LocalSocket in java which accepts "string" (your.local.socket.address)

#define ADDRESS     "/tmp/unix.str" /* ABSOLUTE PATH */
  struct sockaddr_un saun, fsaun;
    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
        perror("server: socket");
        exit(1);
    }
    saun.sun_family = AF_UNIX;
    strcpy(saun.sun_path, ADDRESS);

But the unix domain socket which is at native layer accepts "absolute path". So how can these two parties communicate to each other?

Please share any example if possible

Rohit
  • 6,941
  • 17
  • 58
  • 102

2 Answers2

17

LocalSocket uses the Linux abstract namespace instead of the filesystem. In C these addresses are specified by prepending '\0' to the path.

const char name[] = "\0your.local.socket.address";
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;

// size-1 because abstract socket names are *not* null terminated
memcpy(addr.sun_path, name, sizeof(name) - 1);

Also note that you should not pass sizeof(sockaddr_un) to bind or sendto because all bytes following the '\0' character are interpreted as the abstract socket name. Calculate and pass the real size instead:

int res = sendto(sock, &data, sizeof(data), 0,
                 (struct sockaddr const *) &addr,
                 sizeof(addr.sun_family) + sizeof(name) - 1);
John
  • 2,142
  • 1
  • 19
  • 19
  • This helped me a lot! However I have an issue with getting the client's sockaddr and and length on the server side. I want the client to send a msg to the server (through UDP) and then the server should respond to the client with information. I use recvfrom(_serverSocket, _messageBuffer, INPUT_BUFFER, 0, (struct sockaddr *)&_clientAddress, &_clientAddressLength); on the server side, however _clientAddressLength is zero, and the _clientAddress is empty, and I cannot respond to the client, despite the fact that the msg from client to server was received correctly. – Michael P Aug 01 '15 at 18:42
  • This is my code http://stackoverflow.com/questions/31755790/sockets-unix-domain-udp-c-recvfrom-fail-to-populate-the-source-address?noredirect=1#comment51445587_31755790 – Michael P Aug 01 '15 at 18:42
0

Pro Android C++ with the NDK book, chapter 10 helped me to get started with the same.

Rohit
  • 6,941
  • 17
  • 58
  • 102