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?
I see several issues with your code:
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.
The java code does not pass the SOCKET_DGRAM
type to the constructor; this is new as of API 19.
FILESYSTEM
namespace when creating the LocalSocketAddress
, or'\0'
NUL byte. See also: bind(2)
.LocalSocket socket = new LocalSocket(SOCKET_DGRAM);