Search code examples
androidlocalsocket

Send and Receive UDP using LocalSocket in Android


I got a native app that opens a UnixDomain socket with this code.

struct sockaddr_un local;
int len;
int fd;

fd = socket(AF_UNIX, SOCK_DGRAM, 0);

local.sun_family = AF_UNIX; 
strcpy(local.sun_path, "path.to.socket");

len = strlen(local.sun_path) + sizeof(local.sun_family);

bind(fd, (struct sockaddr*)&local, sizeof(local));

The code above is working because I can see that the socket is created.

Now I want to send a UDP packet from my android app written in Java. I believe I need to use the LocalSocket class. The problem is I don't know how to use the LocalSocket class for UDP. All the tutorials I see is for TCP(SOCK_STREAM).

I tried connecting to the created socket using the codes below but they are giving me errors

LocalSocket socket = new LocalSocket(); 
socket.connect(new LocalSocketAddress( "path.to.socket" ));

This gives me Connection refused error

I also tried binding to the same file but it shows the Address already in use error.

Can I use the LocalSocket class for UDP or it was designed for TCP only?


Solution

  • Problem

    I see several issues with your code:

    1. In your java code, the LocalSocketAddress defaults to the ABSTRACT namespace. However, your native app opens a socket in the LocalSocketAddress.Namespace.FILESYSTEM namespace. However, getting the "address already in use" error implies that the addressing works; this may indicate that your addresses match despite the incorrect namespace.

    2. The java code does not pass the SOCKET_DGRAM type to the constructor; this is new as of API 19.

    Fixes

    Address space

    • either specify the FILESYSTEM namespace when creating the LocalSocketAddress, or
    • in the native app, create the socket in the abstract namespace by prepending a '\0' NUL byte. See also: bind(2).

    Socket Type

    LocalSocket socket = new LocalSocket(SOCKET_DGRAM);