forked from signalsciences/ipv4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathint.go
47 lines (42 loc) · 1.06 KB
/
int.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
package ipv4
import (
"encoding/binary"
"errors"
"fmt"
"net"
)
// FromNetIP converts a IPv4 net.IP to uint32, error
func FromNetIP(ip net.IP) (uint32, error) {
ip = ip.To4()
if ip == nil {
return 0, errors.New("not a IPv4 address")
}
return binary.BigEndian.Uint32(ip), nil
}
// ToNetIP converts a uint32 to a net.IP (net.IPv4 actually)
func ToNetIP(val uint32) net.IP {
return net.IPv4(byte(val>>24), byte(val>>16&0xFF),
byte(val>>8)&0xFF, byte(val&0xFF))
}
// FromDots converts a dotted IPv4 address to a uint32
// http://play.golang.org/p/T5B-6RExlj
// https://groups.google.com/forum/#!topic/golang-nuts/7sC28I57LRY
func FromDots(ipAddr string) (uint32, error) {
ip := net.ParseIP(ipAddr)
if ip == nil {
return 0, errors.New("wrong ipAddr format")
}
ip = ip.To4()
if ip == nil {
return 0, errors.New("not a IPv4 address")
}
return binary.BigEndian.Uint32(ip), nil
}
// ToDots converts a uint32 to a IPv4 Dotted notation
func ToDots(val uint32) string {
return fmt.Sprintf("%d.%d.%d.%d",
val>>24,
(val>>16)&0xFF,
(val>>8)&0xFF,
val&0xFF)
}