Creating a Unix socket
Let’s go through a step-by-step example in Go for creating a UNIX socket server and client. After that, we’ll understand how to use lsof
to inspect the socket:
- For socket path and cleanup, perform the following:
socketPath := "/tmp/example.sock" if err := os.Remove(socketPath); err != nil && !os.IsNotExist(err) { log.Printf("Error removing socket file: %v", err) return }
- Path definition:
socketPath := "/tmp/example.sock"
sets the location for the UNIX socket - Cleanup logic:
os.Remove(socketPath)
attempts to delete any existing socket file at this location to avoid conflicts when starting the server
- Path definition:
- For creating and listening on the UNIX socket:
listener, err := net.Listen("unix", socketPath) if err != nil { log.Printf("Error listening: %v", err) return } defer listener.Close() fmt.Println...