-
Notifications
You must be signed in to change notification settings - Fork 2
/
net.go
98 lines (76 loc) · 2.38 KB
/
net.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
88
89
90
91
92
93
94
95
96
97
98
package goutil
import (
"encoding/binary"
"errors"
"fmt"
"io"
"math/big"
"net"
"net/http"
"os"
)
// ##### Methods #############################################################
func Ipv4ToInt(IPv4Addr net.IP) uint32 {
IPv6Int := big.NewInt(0)
IPv6Int.SetBytes(IPv4Addr.To4())
return uint32(IPv6Int.Int64())
}
// Makes an net.IP struct from an integer
func IntToIpBigEndian(ipAddr uint32) net.IP {
ipByte := make([]byte, 4)
binary.BigEndian.PutUint32(ipByte, ipAddr)
return net.IP(ipByte)
}
// Makes an net.IP struct from an integer
func IntToIpLittleEndian(ipAddr uint32) net.IP {
ipByte := make([]byte, 4)
binary.LittleEndian.PutUint32(ipByte, ipAddr)
return net.IP(ipByte)
}
// Converts a string representation of an IP address to an integer
func InetAton(ipAddr string) (uint32, error) {
ip := net.ParseIP(ipAddr)
if ip == nil {
return 0, errors.New("Wrong IP address format")
}
if ip.To4() == nil {
return 0, errors.New("Wrong IP address format (IPv6")
}
return binary.BigEndian.Uint32(ip.To4()), nil
}
// Converts an integer representation of an IP address to string dotted notation
func InetNtoa(ip uint32) string {
return fmt.Sprintf("%d.%d.%d.%d", byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}
/* RFC1918: IPV4 Private Networks (10.0.0.0/8, 192.168.0.0./16, 172.16.0.0/12)
Should be used by initialising the variables below and then passing into the method to improve performance
rfc1918ten = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(8, 32)}
rfc1918oneninetwo = net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)}
rfc1918oneseventwo = net.IPNet{IP: net.ParseIP("172.16.0.0"), Mask: net.CIDRMask(12, 32)}
*/
func IsIpAddressRfc1918(ten net.IPNet,
oneNineTwo net.IPNet,
oneSevenTwo net.IPNet,
ip net.IP) bool {
return ten.Contains(ip) ||
oneNineTwo.Contains(ip) ||
oneSevenTwo.Contains(ip)
}
//
func DownloadToFile(url string, file string) error {
output, err := os.Create(file)
if err != nil {
return fmt.Errorf(fmt.Sprintf("Error creating download file: %v (%s)", err, file))
}
defer output.Close()
response, err := http.Get(url)
if err != nil {
return fmt.Errorf(fmt.Sprintf("Error downloading from URL: %v (%s)", err, url))
}
defer response.Body.Close()
_, err = io.Copy(output, response.Body)
if err != nil {
return fmt.Errorf(fmt.Sprintf("Error outputing downloaded file: %v (%s)", err, file))
}
return nil
}