Unix Domain Socket

Unix Domain Socket in Android

There are some IPC mechanisms in Android such as AIDL, Messanger, etc and each one has its own pros and cons. based on the requirements, you need to choose the best solution. Unix Domain Socket is a legacy IPC mechanism from Linux/Unix that is available to be used in Android as well.

What is Unix Domain Socket?

UDS or Unix Domain Socket is an IPC (inter-process) mechanism which enables to have bidirectional communication between processes in the same machine. It supports both stream-oriented (TCP) and datagram-oriented (UDP) protocols.

What are the differences between Unix Domain Socket & Network socket?

Network connection uses the underlying network layer to communicate while UDS go through the kernel. It means that the communication in Unix Socket happens entirely on the local machine.

Besides, Unix Socket has less overhead which makes it light and after compared to the Network sockets.

Unix Domain Socket is bound to a file which means that it is relying on the filesystem. Therefore, it can be controlled and protected by the system’s permission. So, other processes can not access it without getting the right permission.

How to use Unix Socket in Android

Android framework has provided LocalSocket and LocalServerSocket to utilize Unix Socket. The steps below are needed to work with Unix Socket in Android:

Server Side

  1. Create a new socket
  2. Accept connection
  3. Get input/output stream
  4. Read/Write to the stream
LocalServerSocket serverSocket = new LocalServerSocket("MyUDS");
senderSocket = serverSocket.accept();
if(senderSocket !=null)
    senderSocket.getOutputStream().write("A message through UDS!";

Client Side

  1. Open a created socket with the same name as the server
  2. Connect to the socket
  3. get input/output stream
  4. Read/Write to the stream
LocalSocket receiverSocket = new LocalSocket();
receiverSocket.connect(new LocalSocketAddress("MyUDS");
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(receiverSocket.getInputStream()));
String message = bufferReader.readLine();
Log.d(TAG,"Received: " + message);

Leave a Comment

Your email address will not be published. Required fields are marked *