-
Notifications
You must be signed in to change notification settings - Fork 0
/
misc.go
87 lines (75 loc) · 1.52 KB
/
misc.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
87
package gportstate
import (
"encoding/binary"
"fmt"
"net"
"unicode/utf16"
"unsafe"
)
/*
#include <stdlib.h>
*/
import "C"
type memBuffer struct {
ptr unsafe.Pointer
size C.size_t
}
func alloc(sz uint32) *memBuffer {
return &memBuffer{
ptr: C.malloc(C.size_t(sz)),
size: C.size_t(sz),
}
}
func (mb *memBuffer) resize(newSize C.size_t) {
mb.ptr = C.realloc(mb.ptr, newSize)
mb.size = newSize
}
func (mb *memBuffer) free() {
C.free(mb.ptr)
}
func inet_aton(ip string) (ip_int uint32) {
ip_byte := net.ParseIP(ip).To4()
for i := 0; i < len(ip_byte); i++ {
ip_int |= uint32(ip_byte[i])
if i < 3 {
ip_int <<= 8
}
}
return
}
func inet_ntoa(ip uint32) string {
return fmt.Sprintf("%d.%d.%d.%d", byte(ip), byte(ip>>8), byte(ip>>16),
byte(ip>>24))
}
func ntohl(i uint32) uint32 {
return binary.BigEndian.Uint32((*(*[4]byte)(unsafe.Pointer(&i)))[:])
}
func htonl(i uint32) uint32 {
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, i)
return *(*uint32)(unsafe.Pointer(&b[0]))
}
func ntohs(i uint16) uint16 {
return binary.BigEndian.Uint16((*(*[2]byte)(unsafe.Pointer(&i)))[:])
}
func htons(i uint16) uint16 {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, i)
return *(*uint16)(unsafe.Pointer(&b[0]))
}
func stringFromUnicode16(s *uint16) string {
if s == nil {
return ""
}
buffer := []uint16{}
ptr := uintptr(unsafe.Pointer(s))
for true {
ch := *(*uint16)(unsafe.Pointer(ptr))
if ch == 0 {
break
}
buffer = append(buffer, ch)
ptr += unsafe.Sizeof(ch)
}
return string(utf16.Decode(buffer))
}