Unix domain sockets

suggest change

A Unix domain socket works like a TCP connection, but between two programs on the same machine, and it is addressed by a file path instead of a host and port. Many local services use them:

Compared to a TCP socket on 127.0.0.1, a Unix socket:

In Dart, Unix sockets use the same classes as TCP: ServerSocket, Socket, RawSocket and HttpServer. The difference is the address you pass in:

final address = InternetAddress('/tmp/app.sock', type: InternetAddressType.unix);

Linux, macOS and Android have been supported since Dart 2.8. Windows has been supported since Dart 3.11, on Windows 10 version 1803 and later, which added AF_UNIX to the OS. Windows only supports some of the features, as described below.

This article covers:

It assumes you know the basics of TCP sockets: reading, writing, closing, and framing messages work exactly the same over a Unix socket. The examples were run with Dart 3.13.4 on Windows 11 and on Linux (Ubuntu in WSL). Output is from Linux, unless it says otherwise; on Windows only the paths are different.

An echo server and client

import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  // A private temp directory keeps the socket path short and unique.
  final dir = await Directory.systemTemp.createTemp('uds');
  final path = '${dir.path}${Platform.pathSeparator}echo.sock';
  final address = InternetAddress(path, type: InternetAddressType.unix);

  // The port argument is required but ignored for Unix sockets.
  final server = await ServerSocket.bind(address, 0);
  print('listening on ${server.address.address} (port ${server.port})');

  server.listen((Socket client) {
    print('server: connection from "${client.remoteAddress.address}"');
    client.listen(client.add, onDone: client.close);
  });

  final socket = await Socket.connect(address, 0);
  print('client: connected to ${socket.remoteAddress.type}');
  socket.write('hello, Unix socket\n');

  final reply = utf8.decoder.bind(socket).join();
  await socket.close();
  print('client: got ${(await reply).trim()}');

  await server.close();
  await dir.delete(recursive: true);
}

Output:

listening on /tmp/udsNNNXJA/echo.sock (port 0)
server: connection from ""
client: connected to InternetAddressType: Unix
client: got hello, Unix socket

Things to note:

The socket file

bind creates a special file at the path, and close deletes it:

import 'dart:io';

Future<void> main() async {
  final dir = Directory.systemTemp.createTempSync('uds');
  final path = '${dir.path}${Platform.pathSeparator}app.sock';
  final address = InternetAddress(path, type: InternetAddressType.unix);

  print('before bind: ${FileSystemEntity.typeSync(path)}');
  final server = await ServerSocket.bind(address, 0);
  print('after bind:  ${FileSystemEntity.typeSync(path)}');
  print('stat:        ${FileStat.statSync(path).type}, '
      'size ${FileStat.statSync(path).size}');

  // A second bind to the same path fails while the file exists.
  try {
    await ServerSocket.bind(address, 0);
  } on SocketException catch (e) {
    print('second bind: ${e.osError?.message}');
  }

  await server.close();
  print('after close: ${FileSystemEntity.typeSync(path)}');
  dir.deleteSync();
}

Output (the same on Windows and Linux):

before bind: notFound
after bind:  unixDomainSock
stat:        unixDomainSock, size 0
second bind: The shared flag to bind() needs to be `true` if binding multiple times on the same path.
after close: notFound

Use FileSystemEntity.typeSync() (or type(), or FileStat) to check for a socket file. It returns FileSystemEntityType.unixDomainSock on every platform. On Windows, socket files are reparse points, and the Dart 3.11 release notes warn that File(path).existsSync() can return false there while it returns true on Linux and macOS. In my test with Dart 3.13.4, it returned true on both, but typeSync() is the portable check. Other tools may not recognize the files either: ls -l in Git Bash on Windows shows a socket as an empty regular file, while on Linux it shows srwxr-xr-x.

The second bind above fails inside Dart, because the same process already owns the path. When another process has bound the path, or a dead process left the file behind, the OS refuses:

SocketException: Failed to create server socket (OS Error: File exists with given unix domain address), address = /tmp/s.sock, port = 0

Stale socket files

ServerSocket.close() deletes the file, but if the process crashes, is killed with kill -9, or exits without closing its server, the file stays. Nobody is listening, so connecting fails (Connection refused on Linux, No connection could be made because the target machine actively refused it on Windows), and the next start of your server fails to bind.

You can't simply delete the file at start-up: if another copy of your program is running, you'd steal its address. The safe way is to try connecting first:

The daemon in the next section does exactly that.

Path length

The path must fit in the OS's sun_path field: at most 107 bytes on Linux and Windows (I tested both), and 103 on macOS. A longer path fails with:

SocketException: Failed to create server socket (OS Error: The length of path exceeds the limit. Check out man 7 unix page), ...

This is easy to hit with paths under deep project or temp directories. Put sockets in a short directory such as /tmp, /run/user/<uid> ($XDG_RUNTIME_DIR), or Directory.systemTemp. A relative path is relative to the current directory, which is another way to keep it short, but it breaks as soon as the server and the client run in different directories.

IPC: a daemon with a control socket

A common use for Unix sockets is a long-running process that you control with a command-line tool: docker talks to dockerd, supervisorctl talks to supervisord. Here's a small daemon that accepts one-line commands:

// daemon.dart
import 'dart:async';
import 'dart:convert';
import 'dart:io';

/// Returns a server socket bound to [path], replacing a stale socket file
/// left behind by a process that crashed. Throws if another live process
/// is already listening there.
Future<ServerSocket> bindUnix(String path) async {
  final address = InternetAddress(path, type: InternetAddressType.unix);
  if (FileSystemEntity.typeSync(path) == FileSystemEntityType.unixDomainSock) {
    try {
      final probe = await Socket.connect(address, 0)
          .timeout(const Duration(seconds: 1));
      probe.destroy();
      throw StateError('another instance is listening on $path');
    } on SocketException {
      // Nobody answered: the file is left over from a dead process.
      File(path).deleteSync();
      print('removed stale socket file');
    }
  }
  return ServerSocket.bind(address, 0);
}

Future<void> main(List<String> args) async {
  final path = args.isNotEmpty
      ? args[0]
      : '${Directory.systemTemp.path}${Platform.pathSeparator}demo-daemon.sock';

  final ServerSocket server;
  try {
    server = await bindUnix(path);
  } on StateError catch (e) {
    stderr.writeln('error: ${e.message}');
    exit(1);
  }
  print('daemon $pid listening on $path');

  final started = DateTime.now();
  var requests = 0;
  final done = Completer<void>();

  Future<void> shutdown() async {
    if (done.isCompleted) return;
    done.complete();
    await server.close(); // also removes the socket file
    print('daemon stopped');
  }

  final sigint = ProcessSignal.sigint.watch().listen((_) => shutdown());

  server.listen((client) {
    utf8.decoder
        .bind(client)
        .transform(const LineSplitter())
        .listen((line) {
      requests++;
      switch (line.trim()) {
        case 'ping':
          client.writeln('pong');
        case 'stats':
          final up = DateTime.now().difference(started).inMilliseconds;
          client.writeln(jsonEncode({'pid': pid, 'requests': requests, 'uptimeMs': up}));
        case 'shutdown':
          client.writeln('bye');
          shutdown();
        case final other:
          client.writeln('error: unknown command "$other"');
      }
    }, onDone: client.close, onError: (_) => client.destroy());
  });

  await done.future;
  await sigint.cancel();
}

The client sends one command per connection and prints the reply:

// ctl.dart
import 'dart:convert';
import 'dart:io';

Future<void> main(List<String> args) async {
  final path = args.length > 1
      ? args[1]
      : '${Directory.systemTemp.path}${Platform.pathSeparator}demo-daemon.sock';
  final address = InternetAddress(path, type: InternetAddressType.unix);

  final Socket socket;
  try {
    socket = await Socket.connect(address, 0);
  } on SocketException catch (e) {
    stderr.writeln('daemon not running (${e.osError?.message ?? e.message})');
    exit(2);
  }

  socket.writeln(args[0]);
  await socket.close(); // one command per connection
  await for (final line in utf8.decoder.bind(socket).transform(const LineSplitter())) {
    print(line);
  }
}

A session on Linux, including a crash simulated with kill -9:

$ dart run daemon.dart &
daemon 3438 listening on /tmp/demo-daemon.sock
$ dart run ctl.dart ping
pong
$ dart run ctl.dart stats
{"pid":3438,"requests":2,"uptimeMs":3373}
$ dart run ctl.dart reload
error: unknown command "reload"
$ dart run daemon.dart
error: another instance is listening on /tmp/demo-daemon.sock
$ kill -9 %1
$ ls -l /tmp/demo-daemon.sock
srwxr-xr-x 1 kjk kjk 0 Oct 18 01:07 /tmp/demo-daemon.sock
$ dart run ctl.dart ping
daemon not running (Connection refused)
$ dart run daemon.dart &
removed stale socket file
daemon 3544 listening on /tmp/demo-daemon.sock
$ dart run ctl.dart shutdown
daemon stopped
bye

On Windows the same programs work unchanged, and the socket is C:\Users\<you>\AppData\Local\Temp\demo-daemon.sock. After Stop-Process -Force the next daemon also printed removed stale socket file.

Notes on the design:

HTTP over a Unix socket

HttpServer.bind takes the same address. On the client side, HttpClient has no setting for a Unix socket, but its connectionFactory lets you open the connection yourself. The URL then only provides the path and the Host header:

import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  final dir = await Directory.systemTemp.createTemp('uds');
  final path = '${dir.path}${Platform.pathSeparator}api.sock';
  final address = InternetAddress(path, type: InternetAddressType.unix);

  final server = await HttpServer.bind(address, 0);
  print('serving on ${server.address.address}');
  server.listen((request) {
    final info = request.connectionInfo;
    print('server: ${request.method} ${request.uri} '
        'host=${request.headers.host} '
        'remote=${info?.remoteAddress.type}');
    request.response
      ..headers.contentType = ContentType.json
      ..write(jsonEncode({'path': request.uri.path, 'ok': true}))
      ..close();
  });

  final client = HttpClient()
    ..connectionFactory = (uri, proxyHost, proxyPort) =>
        Socket.startConnect(address, 0);

  final request = await client.getUrl(Uri.parse('http://localhost/v1/status'));
  final response = await request.close();
  print('client: ${response.statusCode} ${response.headers.contentType}');
  print('client: ${await response.transform(utf8.decoder).join()}');

  client.close();
  await server.close();
  await dir.delete(recursive: true);
}

Output (Windows):

serving on C:\Users\kjk\AppData\Local\Temp\udsa120d51b\api.sock
server: GET /v1/status host=localhost remote=InternetAddressType: Unix
client: 200 application/json; charset=utf-8
client: {"path":"/v1/status","ok":true}

connectionFactory is called for every new connection and must return a Future<ConnectionTask<Socket>>, which is what Socket.startConnect returns. Keep-alive, chunked encoding and everything else in HttpClient work as usual. The same server code works with everything in An HTTP server, including Shelf: shelf_io.serve(handler, address, 0) accepts a Unix InternetAddress too.

curl can talk to it with --unix-socket. This works on Linux and macOS, and with the curl.exe that ships with Windows 10 and 11. Here's a small server that stops when it gets /quit:

// hserve.dart
import 'dart:io';

Future<void> main(List<String> args) async {
  final path = args[0];
  final server = await HttpServer.bind(
      InternetAddress(path, type: InternetAddressType.unix), 0);
  print('listening on $path');
  // Ctrl+C closes the server, which also deletes the socket file.
  final sigint = ProcessSignal.sigint.watch().listen((_) => server.close());

  await for (final request in server) {
    print('${request.method} ${request.uri}');
    request.response.writeln('hello from Dart, you asked for ${request.uri}');
    await request.response.close();
    if (request.uri.path == '/quit') await server.close();
  }
  await sigint.cancel();
  print('stopped');
}

With dart run hserve.dart C:\Users\kjk\AppData\Local\Temp\pbw-uds\h.sock running in another window:

> curl -s --unix-socket C:\Users\kjk\AppData\Local\Temp\pbw-uds\h.sock http://localhost/status
hello from Dart, you asked for /status
> curl -s --unix-socket C:\Users\kjk\AppData\Local\Temp\pbw-uds\h.sock http://localhost/quit
hello from Dart, you asked for /quit

The server printed:

listening on C:\Users\kjk\AppData\Local\Temp\pbw-uds\h.sock
GET /status
GET /quit
stopped

Serving HTTP on a Unix socket is a common setup behind a reverse proxy on the same machine. nginx connects with proxy_pass http://unix:/run/myapp.sock;, and the app needs no port and can't be reached from outside.

Talking to the Docker daemon

The Docker Engine API is plain HTTP and JSON over /var/run/docker.sock, so the HttpClient trick above is all you need for a small client:

import 'dart:convert';
import 'dart:io';

/// A tiny Docker Engine API client that talks HTTP over the daemon's
/// Unix socket, the same way the `docker` CLI does.
class DockerClient {
  DockerClient([String socketPath = '/var/run/docker.sock']) {
    final address = InternetAddress(socketPath, type: InternetAddressType.unix);
    // Every connection the client opens goes to the socket, whatever the URL.
    _http.connectionFactory =
        (uri, proxyHost, proxyPort) => Socket.startConnect(address, 0);
  }

  final _http = HttpClient();

  Future<Object?> get(String path) async {
    // The host name is required by HTTP but ignored by the daemon.
    final request = await _http.getUrl(Uri.parse('http://docker$path'));
    final response = await request.close();
    final body = await response.transform(utf8.decoder).join();
    if (response.statusCode != HttpStatus.ok) {
      throw HttpException('${response.statusCode}: $body');
    }
    return jsonDecode(body);
  }

  void close() => _http.close();
}

Future<void> main() async {
  // DOCKER_HOST looks like unix:///var/run/docker.sock
  final host = Platform.environment['DOCKER_HOST'];
  final docker = host != null && host.startsWith('unix://')
      ? DockerClient(host.substring('unix://'.length))
      : DockerClient();
  try {
    final version = await docker.get('/version') as Map<String, dynamic>;
    print('Docker ${version['Version']} (API ${version['ApiVersion']}) '
        'on ${version['Os']}/${version['Arch']}');

    final containers = await docker.get('/containers/json?all=true') as List;
    for (final c in containers.cast<Map<String, dynamic>>()) {
      print('${(c['Names'] as List).first}  ${c['Image']}  ${c['State']}');
    }
  } on SocketException catch (e) {
    print('cannot reach Docker: ${e.osError?.message ?? e.message}');
  } finally {
    docker.close();
  }
}

It prints the Docker version, then one line per container with its name, image and state. I tested it against a small fake server that returned Docker-shaped JSON. On a machine without Docker it prints:

cannot reach Docker: No such file or directory

Things to know:

Connecting to PostgreSQL through its socket

Local PostgreSQL servers listen on a socket named .s.PGSQL.<port> in each directory listed in unix_socket_directories (/var/run/postgresql on Debian and Ubuntu, /tmp on macOS with Homebrew). The postgres package (3.x) connects to it when you set isUnixSocket: true and pass the full path of the socket file as host:

import 'dart:io';

import 'package:postgres/postgres.dart';

Future<void> main() async {
  // The socket file is <unix_socket_directories>/.s.PGSQL.<port>.
  // On Debian/Ubuntu that is /var/run/postgresql/.s.PGSQL.5432.
  final socketPath = Platform.environment['PGSOCKET'] ??
      '/var/run/postgresql/.s.PGSQL.5432';

  final conn = await Connection.open(
    Endpoint(
      host: socketPath,
      isUnixSocket: true,
      database: 'postgres',
      username: 'postgres',
    ),
    // TLS over a local socket adds nothing; the server would refuse it anyway.
    settings: ConnectionSettings(sslMode: SslMode.disable),
  );
  try {
    final rows = await conn.execute(
        "SELECT current_user, inet_server_addr() IS NULL AS via_socket, "
        "split_part(version(), ' ', 2) AS version");
    final [user, viaSocket, version] = rows.single;
    print('user=$user via_socket=$viaSocket server=$version');
  } finally {
    await conn.close();
  }
}

I ran it on Windows against PostgreSQL 18, which supports Unix sockets on Windows too. The server was configured with listen_addresses = '', so it had no TCP port at all, and unix_socket_directories pointed at a short temp directory:

user=postgres via_socket=true server=18.0

inet_server_addr() returns NULL for socket connections, which confirms the connection didn't use TCP. On Linux, the default pg_hba.conf usually allows peer authentication on the socket: the server asks the kernel which OS user connected and lets you log in as the database user with the same name, without a password. That's a common reason to prefer the socket for local tools and cron jobs. For everything else about the package, see PostgreSQL.

MySQL works the same way. With mysql_client, pass host: InternetAddress('/var/run/mysqld/mysqld.sock', type: InternetAddressType.unix), as shown in MySQL.

Passing open files to another process

Unix sockets can carry open file descriptors as well as bytes (SCM_RIGHTS). The receiving process gets its own handle to the same open file, even if it couldn't open the path itself. Dart supports this on Linux and macOS with RawSocket.sendMessage and RawSocket.readMessage:

import 'dart:async';
import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  if (Platform.isWindows || Platform.isAndroid) {
    print('passing handles is not supported on ${Platform.operatingSystem}');
    return;
  }
  final dir = Directory.systemTemp.createTempSync('uds');
  final sep = Platform.pathSeparator;
  final note = File('${dir.path}${sep}note.txt')..writeAsStringSync('secret note\n');
  final address = InternetAddress('${dir.path}${sep}fd.sock', type: InternetAddressType.unix);

  // Receiver: gets a message plus an open file handle.
  final server = await RawServerSocket.bind(address, 0);
  final received = Completer<void>();
  server.listen((conn) {
    conn.listen((event) {
      if (event != RawSocketEvent.read) return;
      final msg = conn.readMessage();
      if (msg == null) return;
      print('receiver: data "${utf8.decode(msg.data)}"');
      for (final cmsg in msg.controlMessages) {
        for (final handle in cmsg.extractHandles()) {
          final file = handle.toFile();
          file.setPositionSync(0);
          print('receiver: file says "${utf8.decode(file.readSync(100)).trim()}"');
          file.closeSync();
        }
      }
      conn.close();
      received.complete();
    });
  });

  // Sender: opens the file and passes the open descriptor, not the path.
  final client = await RawSocket.connect(address, 0);
  final opened = note.openSync();
  try {
    client.sendMessage(
        [SocketControlMessage.fromHandles([ResourceHandle.fromFile(opened)])],
        utf8.encode('here is a file'));
    await received.future;
  } catch (e) {
    print('sendMessage failed: $e');
  }
  opened.closeSync();
  client.close();
  await server.close();
  dir.deleteSync(recursive: true);
}

Output (Linux):

receiver: data "here is a file"
receiver: file says "secret note"

On Windows it prints passing handles is not supported on windows. Without the check, the call fails there with an UnsupportedError.

Both sides are in one process here to keep the example short. The real use is between processes: a privileged process opens a file or a socket and hands it to an unprivileged worker, or a server passes its listening socket to its replacement during a restart without downtime. ResourceHandle also has fromSocket, fromRawSocket, fromStdin and fromStdout, and matching toSocket() and friends on the receiving side.

Platform differences

Linux, macOS Android Windows (Dart 3.11+)
ServerSocket, Socket, HttpServer yes yes yes, Windows 10 1803+
socket file type unixDomainSock unixDomainSock unixDomainSock (a reparse point)
abstract names (@name) Linux only yes no
passing handles (sendMessage) yes no no
datagram sockets no no no
max path length 107 (Linux), 103 (macOS) 107 107
file permissions limit access yes yes NTFS ACLs of the directory

Some details:

Permissions and where to put the socket

Anyone who can open the socket file can connect, so its location is your access control:

Common pitfalls

Summary

Task How
Address InternetAddress(path, type: InternetAddressType.unix)
Listen await ServerSocket.bind(address, 0) (port ignored)
Connect await Socket.connect(address, 0)
HTTP server await HttpServer.bind(address, 0)
HTTP client HttpClient()..connectionFactory = (u, h, p) => Socket.startConnect(address, 0)
Test from the shell curl --unix-socket <path> http://localhost/...
Is it a socket file? FileSystemEntity.typeSync(path) == FileSystemEntityType.unixDomainSock
Remove the file await server.close()
Stale file after a crash connect first; if refused, delete it, then bind
Abstract socket (Linux, Android) path starting with @
Pass an open file (Linux, macOS) RawSocket.sendMessage([SocketControlMessage.fromHandles([...])], data)
PostgreSQL Endpoint(host: '/var/run/postgresql/.s.PGSQL.5432', isUnixSocket: true, ...)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents