Unix domain sockets
suggest changeA 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:
- the Docker daemon listens on
/var/run/docker.sock - PostgreSQL creates
/var/run/postgresql/.s.PGSQL.5432and MySQL creates/var/run/mysqld/mysqld.sock - systemd, D-Bus, containerd and many language servers and editor daemons use them too
Compared to a TCP socket on 127.0.0.1, a Unix socket:
- can't be reached from the network, even by mistake
- needs no port, so two programs can't fight over port 8080
- is protected by file system permissions: whoever can't access the socket file (or its directory) can't connect
- skips the TCP/IP stack, so it has a bit less overhead
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:
- an echo server and client
- how the socket file is created, removed and left behind
- IPC between processes: a daemon with a control socket and a command-line client
- HTTP over a Unix socket, with
HttpServer,HttpClientandcurl - talking to the Docker daemon and to PostgreSQL over their sockets
- passing open files to another process (Linux and macOS)
- platform differences and common pitfalls
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:
InternetAddress(path, type: InternetAddressType.unix)doesn't touch the file system. It just wraps the path.address.addressreturns the path.bind,connectandstartConnecttake a port, but ignore it for Unix sockets. Pass0. TheportandremotePortgetters always return0.- The client's socket has no name, so on the server
remoteAddress.addressis an empty string. There's no equivalent of the client's IP address. If you need to know who is connecting, protect the socket file instead (see Permissions). - Everything else is the same as TCP: the socket is a
Stream<Uint8List>and anIOSink,close()closes your sending side anddestroy()closes both. Unix sockets are streams of bytes too, so you still need to frame your messages.
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:
- connection succeeds: another instance is running, so don't start
- connection refused: the file is stale, so delete it and bind
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:
- Ctrl+C (
SIGINT, which works on Windows too) and theshutdowncommand both go throughserver.close(), so the socket file is removed. See Signals and graceful shutdown.kill -9can't be caught, which is why the stale-file check is still needed. - The subscription to
ProcessSignal.sigint.watch()keeps the program alive, so cancel it at the end. Otherwise the daemon would keep running afterserver.close(). - One command per connection keeps the protocol trivial: the client half-closes with
socket.close(), the server's line stream ends, and the server closes its side. For a long conversation over one connection, use a request/response client like the one in TCP sockets. statsreturns JSON, which keeps the reply easy to parse for scripts. You could also run JSON-RPC or HTTP over the socket.
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:
- On Linux, the socket belongs to
rootand thedockergroup. If you're in neither, connecting fails withPermission denied. Membership in thedockergroup is effectively root access, so don't widen the permissions of this socket. - Docker Desktop on macOS also provides the socket (
/var/run/docker.sock, or~/.docker/run/docker.sock), and so do Podman and Colima. Each setsDOCKER_HOSTor a Docker context to point at it. - Docker Desktop on Windows uses a named pipe (
npipe:////./pipe/docker_engine), not a Unix socket, anddart:iocan't open named pipes as sockets. From WSL, the Linux socket works. - To pin the API version, prefix paths with it, for example
/v1.47/containers/json.
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:
- Abstract sockets (Linux and Android) have a name that starts with
@and no file. They disappear automatically when the last socket closes, so they can't go stale. On Windows and macOS,InternetAddress('@name', type: InternetAddressType.unix)is an ordinary relative path: binding it created a socket file named@namein the current directory in my test on Windows. - Datagrams: the 3.11 release notes list datagram sockets and ancillary data as unsupported on Windows. In
dart:ioyou can't use datagram Unix sockets on any platform:RawDatagramSocket.bindwith a Unix address throwsSocketException: Cannot bind datagram socket on non-IPv4/IPv6 addresson Linux too. - Error messages differ. Connecting to a missing socket fails with
No such file or directoryon Linux, and on Windows I saw bothNo connection could be made because the target machine actively refused itandA socket operation encountered a dead network. Checke.osError?.errorCodeor treat anySocketExceptionon connect as "not running", asctl.dartdoes. shared: trueworks for Unix sockets as it does for TCP: several isolates in the same process can bind the same path and share the connections (see TCP sockets).- Unix sockets aren't available on the web.
Permissions and where to put the socket
Anyone who can open the socket file can connect, so its location is your access control:
- On Linux and macOS a new socket gets the permissions of the process's umask (
srwxr-xr-xabove). Connecting requires write permission on the socket file.dart:iohas nochmod, so the simplest way to restrict access is to create the socket in a directory only you can access, for example a temp directory afterProcess.run('chmod', ['700', dir.path]), or$XDG_RUNTIME_DIR(/run/user/<uid>), which is already private. See Running OS commands. - System services usually put sockets in
/run/<service>/and give the group access (likedocker). - On Windows, access is controlled by the ACL of the directory.
%TEMP%(Directory.systemTemp) is private to the user by default. - Don't put sockets in a shared directory under a predictable name unless the program checks who created it. Another user could create the path first.
Common pitfalls
- Forgetting to remove the socket file. Always end with
server.close(), also on Ctrl+C, and handle stale files at start-up with the connect-then-delete check. Don't delete the file without checking first, or you'll take the address from a running instance. - Paths that are too long. 107 bytes goes quickly under a deep project or temp directory. Build the path from a short base directory.
- Using
File(path).existsSync()to check for a socket. UseFileSystemEntity.typeSync(path) == FileSystemEntityType.unixDomainSock, which works on all platforms. - Expecting a peer address.
remoteAddress.addressis empty on the server. Use file permissions (or, with PostgreSQL,peerauthentication) to control who connects, or authenticate inside your protocol. - Passing a port that matters. The port is ignored. Code that logs
server.portor uses it in URLs will show0. - Leaving server-side sockets unread. A connection you never listen to (or
destroy()) stays open. In my test on Windows, a server that wrote a reply and calledclose()on a connection it never read from kept the program running afterserver.close(). Always consume or destroy each accepted socket. - Assuming a Windows feature from Linux works. Abstract names, handle passing and named pipes are not available, as described in Platform differences.
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, ...) |