Unix domain socket server and client
There are three types of unix domain socket.
"unix" corresponds to SOCK_STREAM
"unixdomain" corresponds to SOCK_DGRAM
"unixpacket" corresponds to SOCK_SEQPACKET
When you write a "unix" or "unixpacket" server, use ListenUnix().
l, err := net.ListenUnix("unix", &net.UnixAddr{"/tmp/unixdomain", "unix"}) if err != nil { panic(err) } defer os.Remove("/tmp/unixdomain") for { conn, err := l.AcceptUnix() if err != nil { panic(err) } var buf [1024]byte n, err := conn.Read(buf[:]) if err != nil { panic(err) } fmt.Printf("%s\n", string(buf[:n])); conn.Close() }
"unixgram" server uses ListenUnixgram().
conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{"/tmp/unixdomain", "unixgram"}) if err != nil { panic(err) } defer os.Remove("/tmp/unixdomain") for { var buf [1024]byte n, err := conn.Read(buf[:]) if err != nil { panic(err) } fmt.Printf("%s\n", string(buf[:n])); }
type := "unix" // or "unixgram" or "unixpacket" laddr := net.UnixAddr{"/tmp/unixdomaincli", type} conn, err := net.DialUnix(type, &laddr/*can be nil*/, &net.UnixAddr{"/tmp/unixdomain", type}) if err != nil { panic(err) } defer os.Remove("/tmp/unixdomaincli") _, err = conn.Write([]byte("hello")) if err != nil { panic(err) } conn.Close()