Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save YongfuHou/b0baea8d7c98fe4798c45d0f7004c743 to your computer and use it in GitHub Desktop.
Save YongfuHou/b0baea8d7c98fe4798c45d0f7004c743 to your computer and use it in GitHub Desktop.
getting the pid, uid and gid of a remote unix-socket connection in golang
package main

import (
        "fmt"
        "net"
        "reflect"
        "runtime"
        "syscall"
)

func main() {
        l, err := net.Listen("unix", "/tmp/echo.sock")
        if err != nil {
                println("listen error", err.Error())
                return
        }

        for {
                fd, err := l.Accept()
                if err != nil {
                        println("accept error", err.Error())
                        return
                }

                ptrVal := reflect.ValueOf(fd)
                val2 := reflect.Indirect(ptrVal)

                // which is a net.conn from which we get the 'fd' field
                fdmember := val2.FieldByName("fd")
                val3 := reflect.Indirect(fdmember)

                // which is a netFD from which we get the 'sysfd' field
                netFdPtr := val3.FieldByName("sysfd")
                fmt.Printf("netFDPtr= %v\n", netFdPtr)

                // which is the system socket (type is plateform specific - Int for linux)
                if runtime.GOOS == "linux" {
                        cfd := int(netFdPtr.Int())
                        ucred, _ := syscall.GetsockoptUcred(cfd, syscall.SOL_SOCKET, syscall.SO_PEERCRED)

                        fmt.Printf("peer_pid: %d\n", ucred.Pid)
                        fmt.Printf("peer_uid: %d\n", ucred.Uid)
                        fmt.Printf("peer_gid: %d\n", ucred.Gid)

                }
        }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment