Prove me wrong! It is impossible to to get the socket file descriptor

432 views
Skip to first unread message

cru...@gmail.com

unread,
Aug 21, 2015, 9:05:39 PM8/21/15
to golang-nuts
Hello,

I'm writing a go program which accepts connections over a unix socket.  I need the file descriptor (integer) of the socket.  For example:

    listenSock, _ := net.Listen("unix", "/tmp/my.socket")

    conn, _ := listenSock.Accept()

    var fd int
    fd = conn.PleaseGetMeTheFileDescriptorInteger()


I need the file descriptor so I can make a C call to getpeereid() so I can verify the identity of the process which is connecting to me (security).  Is it impossible?

Thanks!
- Adam B.

Ian Lance Taylor

unread,
Aug 21, 2015, 9:22:47 PM8/21/15
to cru...@gmail.com, golang-nuts
c.File().Fd()

Make sure to read the documentation of those methods.

I wonder if we could add Getpeereid to the net package for systems and
connection types for which it works.

Ian

Staven

unread,
Aug 22, 2015, 10:17:52 AM8/22/15
to golang-nuts
What's with the clickbait subject?

cru...@gmail.com

unread,
Aug 22, 2015, 11:43:32 AM8/22/15
to golang-nuts, cru...@gmail.com
Thanks for the response, Ian.  In my reading of the docs, UnixConn.File() returns a different file descriptor ("The returned os.File's file descriptor is different from the connection's").

Sorry for the subject line.  It was a Friday afternoon and I was mad about wasting an hour on something that should have taken 30 seconds.

Matt Harden

unread,
Aug 22, 2015, 11:47:04 AM8/22/15
to cru...@gmail.com, golang-nuts
It's a dup() of the conn's fd. It's the same connection. You can close the connection and then your fd will be the only one associated with the connection.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Brad Fitzpatrick

unread,
Aug 22, 2015, 11:55:27 AM8/22/15
to golang-nuts
On Sat, Aug 22, 2015 at 11:17 PM, Staven <sta...@staven.pl> wrote:
What's with the clickbait subject?

You won't BELIEVE these 6 stupid gopher tricks! https://talks.golang.org/2015/tricks.slide 

cru...@gmail.com

unread,
Aug 22, 2015, 3:40:34 PM8/22/15
to golang-nuts, cru...@gmail.com
OK, I'll give it a try with the dup'd FD on Monday.  Thanks folks!

cru...@gmail.com

unread,
Aug 24, 2015, 12:04:12 PM8/24/15
to golang-nuts
Using the dup'd descriptor from UnixConn.File().Fd() works perfectly.  Thanks Matt!

For anybody else needing getpeerid() functionality I was able to use syscall.GetsockoptUcred() instead.  Something like:

f, _ := unixSock.File()
fd := int(f.Fd())
pcred, _ := syscall.GetsockoptUcred(fd, syscall.SOL_SOCKET, syscall.SO_PEERCRED)
f.Close()
fmt.Println("peer uid and gid:", pcred.Uid, pcred.Gid)



Reply all
Reply to author
Forward
0 new messages