1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // +build darwin freebsd linux openbsd
14 func newFileFD(f *os.File) (nfd *netFD, err error) {
15 fd, errno := syscall.Dup(f.Fd())
17 return nil, os.NewSyscallError("dup", errno)
20 proto, errno := syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_TYPE)
22 return nil, os.NewSyscallError("getsockopt", errno)
25 family := syscall.AF_UNSPEC
26 toAddr := sockaddrToTCP
27 sa, _ := syscall.Getsockname(fd)
32 case *syscall.SockaddrInet4:
33 family = syscall.AF_INET
34 if proto == syscall.SOCK_DGRAM {
35 toAddr = sockaddrToUDP
36 } else if proto == syscall.SOCK_RAW {
39 case *syscall.SockaddrInet6:
40 family = syscall.AF_INET6
41 if proto == syscall.SOCK_DGRAM {
42 toAddr = sockaddrToUDP
43 } else if proto == syscall.SOCK_RAW {
46 case *syscall.SockaddrUnix:
47 family = syscall.AF_UNIX
48 toAddr = sockaddrToUnix
49 if proto == syscall.SOCK_DGRAM {
50 toAddr = sockaddrToUnixgram
51 } else if proto == syscall.SOCK_SEQPACKET {
52 toAddr = sockaddrToUnixpacket
56 sa, _ = syscall.Getpeername(fd)
59 if nfd, err = newFD(fd, family, proto, laddr.Network()); err != nil {
62 nfd.setAddr(laddr, raddr)
66 // FileConn returns a copy of the network connection corresponding to
67 // the open file f. It is the caller's responsibility to close f when
68 // finished. Closing c does not affect f, and closing f does not
70 func FileConn(f *os.File) (c Conn, err error) {
71 fd, err := newFileFD(f)
75 switch fd.laddr.(type) {
77 return newTCPConn(fd), nil
79 return newUDPConn(fd), nil
81 return newUnixConn(fd), nil
83 return newIPConn(fd), nil
89 // FileListener returns a copy of the network listener corresponding
90 // to the open file f. It is the caller's responsibility to close l
91 // when finished. Closing c does not affect l, and closing l does not
93 func FileListener(f *os.File) (l Listener, err error) {
94 fd, err := newFileFD(f)
98 switch laddr := fd.laddr.(type) {
100 return &TCPListener{fd}, nil
102 return &UnixListener{fd, laddr.Name}, nil
105 return nil, os.EINVAL
108 // FilePacketConn returns a copy of the packet network connection
109 // corresponding to the open file f. It is the caller's
110 // responsibility to close f when finished. Closing c does not affect
111 // f, and closing f does not affect c.
112 func FilePacketConn(f *os.File) (c PacketConn, err error) {
113 fd, err := newFileFD(f)
117 switch fd.laddr.(type) {
119 return newUDPConn(fd), nil
121 return newUnixConn(fd), nil
124 return nil, os.EINVAL