Understanding Socket paths with @ (Abstract Sockets)

1.1k views Asked by At

What is @ in the socket path?

I am opening a unix socket using LocalServerSocket().

root@device:/dev/socket # netstat -a
.......
Proto RefCnt Flags       Type       State         I-Node Path
Active UNIX domain sockets (servers and established)
unix  2      [ ACC ]     STREAM     LISTENING      37305 @/storage/my_sock
unix  20     [ ]         DGRAM                      7231 /dev/socket/logdw
unix  2      [ ACC ]     SEQPACKET  LISTENING       7234 /dev/socket/logdr
unix  2      [ ACC ]     STREAM     LISTENING       7236 /dev/socket/logd
.......

Unlike for other sockets, my sockets is being prefixed with @. Also, I went and checked /storage partition. I could not find this socket generated there.

My code where I am creating the socket is shown below.

LocalServerSocket lss = new LocalServerSocket("/storage/my_sock");
LocalSocket sock = lss.accept();
InputStream ins = sock.getInputStream();

My idea is to open a local server socket from Java and use to as a communication channel to interact with a native C application. But As the path is invalid, I am not able to achieve this.

1

There are 1 answers

0
Sandeep On BEST ANSWER

@ in the unix socket paths indicate that they are abstract sockets. Abstact sockets cannot be seen physically on the disk. In android LocalServerSocket() creates abstract sockets.

Android :

LocalServerSocket lss = new LocalServerSocket("my_sock");
LocalSocket sock = lss.accept();
InputStream ins = sock.getInputStream();

Native :

From native application in order to open the same abstract socket, define sun_path as follows.

sock.sun_family = AF_UNIX;
sock.sun_path[0] = '\0'
strcpy(&sock.sun_path[1], "my_sock");
sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
len_addr = offsetof(struct sockaddr_un, sun_path) + strlen("my_sock") + 1;
res = connect(sock_fd, (struct sockaddr *)&sock, len_addr);

Note that the first byte of sun_path is '\0' and that the actual name continues from &sun_path[1]. By following this naming convention for naming the socket, the system identifies that we want to operate on an abstract socket and provides one for us.