This repository has been archived by the owner on Jan 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
sockaddr_windows.go
86 lines (74 loc) · 2.08 KB
/
sockaddr_windows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package sockaddr
import (
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
func sockaddrToAny(sa windows.Sockaddr) (*windows.RawSockaddrAny, Socklen, error) {
if sa == nil {
return nil, 0, syscall.EINVAL
}
switch sa := sa.(type) {
case *windows.SockaddrInet4:
if sa.Port < 0 || sa.Port > 0xFFFF {
return nil, 0, syscall.EINVAL
}
raw := new(windows.RawSockaddrAny)
raw.Addr.Family = windows.AF_INET
raw4 := (*windows.RawSockaddrInet4)(unsafe.Pointer(raw))
p := (*[2]byte)(unsafe.Pointer(&raw4.Port))
p[0] = byte(sa.Port >> 8)
p[1] = byte(sa.Port)
for i := 0; i < len(sa.Addr); i++ {
raw4.Addr[i] = sa.Addr[i]
}
return raw, Socklen(unsafe.Sizeof(*raw4)), nil
case *windows.SockaddrInet6:
if sa.Port < 0 || sa.Port > 0xFFFF {
return nil, 0, syscall.EINVAL
}
raw := new(windows.RawSockaddrAny)
raw.Addr.Family = windows.AF_INET6
raw6 := (*windows.RawSockaddrInet6)(unsafe.Pointer(raw))
p := (*[2]byte)(unsafe.Pointer(&raw6.Port))
p[0] = byte(sa.Port >> 8)
p[1] = byte(sa.Port)
raw6.Scope_id = sa.ZoneId
for i := 0; i < len(sa.Addr); i++ {
raw6.Addr[i] = sa.Addr[i]
}
return raw, Socklen(unsafe.Sizeof(*raw6)), nil
case *windows.SockaddrUnix:
return nil, 0, syscall.EWINDOWS
}
return nil, 0, syscall.EAFNOSUPPORT
}
func anyToSockaddr(rsa *windows.RawSockaddrAny) (windows.Sockaddr, error) {
if rsa == nil {
return nil, syscall.EINVAL
}
switch rsa.Addr.Family {
case windows.AF_UNIX:
return nil, syscall.EWINDOWS
case windows.AF_INET:
pp := (*windows.RawSockaddrInet4)(unsafe.Pointer(rsa))
sa := new(windows.SockaddrInet4)
p := (*[2]byte)(unsafe.Pointer(&pp.Port))
sa.Port = int(p[0])<<8 + int(p[1])
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
case windows.AF_INET6:
pp := (*windows.RawSockaddrInet6)(unsafe.Pointer(rsa))
sa := new(windows.SockaddrInet6)
p := (*[2]byte)(unsafe.Pointer(&pp.Port))
sa.Port = int(p[0])<<8 + int(p[1])
sa.ZoneId = pp.Scope_id
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
}
return nil, syscall.EAFNOSUPPORT
}