-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipconv.go
101 lines (88 loc) · 2.15 KB
/
ipconv.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
99
100
101
// Copyright 2020 Kiyon Lin All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package ipconv is a library providing utility functions to convert
// ip.
package ipconv
import (
"fmt"
"strconv"
"unsafe"
)
// Version of current package
const Version = "0.1.1"
type ipv4Error struct {
ip string
}
func (e ipv4Error) Error() string {
return fmt.Sprintf("ipconv: invalid ipv4 %s", e.ip)
}
// V42Long converts an ipv4 string to an uint32 integer.
// Panic if format of ip is not ipv4
func V42Long(ip string) uint32 {
if long, err := SafeV42Long(ip); err != nil {
panic(err)
} else {
return long
}
}
// SafeV42Long converts an ipv4 string to an uint32 integer.
// An error returns if format of ip is not ipv4
func SafeV42Long(ip string) (long uint32, err error) {
l := len(ip)
if l < 7 || l > 15 {
return 0, ipv4Error{ip}
}
var (
n uint32
b = 24
)
for i := 0; i < l; i++ {
c := ip[i]
switch {
case c == '.':
if b <= 0 {
return 0, ipv4Error{ip}
}
long |= n << b
n, b = 0, b-8
case c >= '0' && c <= '9':
n = n*10 + uint32(c-'0')
if n > 255 {
return 0, ipv4Error{ip}
}
default:
return 0, ipv4Error{ip}
}
}
return long | n, nil
}
var n2s [256]string
func init() {
for i := 0; i < 256; i++ {
n2s[i] = strconv.Itoa(i)
}
}
// Long2V4 convert an uint32 integer to ipv4 string
func Long2V4(ip uint32) string {
b := make([]byte, 0, 15)
b = append(b, n2s[byte(ip>>24)]...)
b = append(b, '.')
b = append(b, n2s[byte(ip>>16)]...)
b = append(b, '.')
b = append(b, n2s[byte(ip>>8)]...)
b = append(b, '.')
b = append(b, n2s[byte(ip)]...)
/* #nosec G103 */
return *(*string)(unsafe.Pointer(&b))
}