Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
golang ipv4 string to uint32.
package ipconv
import (
"fmt"
"strconv"
"strings"
)
func Conv(ip string) (uint32, error) {
segs := strings.Split(ip, ".")
if len(segs) != 4 {
return 0, fmt.Errorf("invalid ip4 input string")
}
s := make([]int, 4)
for i := 0; i < 4; i++ {
n, err := strconv.Atoi(segs[i])
if err != nil {
return 0, err
}
if n <= 0 || n > 255 {
return 0, fmt.Errorf("invalid ip4 input string")
}
s[i] = n
}
rv := uint32(s[0]<<24 | s[1]<<16 | s[2]<<8 | s[3])
return rv, nil
}
package ipconv
import (
"testing"
"gotest.tools/assert"
)
func Test_Conv(t *testing.T) {
var n uint32
var err error
n, err = Conv("1.1.1.1")
assert.Assert(t, err == nil)
assert.Equal(t, n, uint32(16843009))
n, err = Conv("192.168.1.1")
assert.Assert(t, err == nil)
assert.Equal(t, n, uint32(3232235777))
n, err = Conv("223.5.5.5")
assert.Assert(t, err == nil)
assert.Equal(t, n, uint32(3741648133))
n, err = Conv("172.16.254.1")
assert.Assert(t, err == nil)
assert.Equal(t, n, uint32(2886794753))
/* invalid input */
// less than 4-part
n, err = Conv("1.1.1")
assert.Assert(t, err != nil)
assert.Equal(t, n, uint32(0))
// more than 4-part
n, err = Conv("1.1.1.1.1")
assert.Assert(t, err != nil)
assert.Equal(t, n, uint32(0))
// less than 1
n, err = Conv("0.1.1.1")
assert.Assert(t, err != nil)
assert.Equal(t, n, uint32(0))
// greater than 255
n, err = Conv("1.1.256.1")
assert.Assert(t, err != nil)
assert.Equal(t, n, uint32(0))
// greater than 255
n, err = Conv("1.1.2345.1")
assert.Assert(t, err != nil)
assert.Equal(t, n, uint32(0))
// not even a number...
n, err = Conv("1.1.a.1")
assert.Assert(t, err != nil)
assert.Equal(t, n, uint32(0))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.