Skip to content
Snippets Groups Projects
Unverified Commit 55cf3d2a authored by Maximilian Wilhelm's avatar Maximilian Wilhelm Committed by GitHub
Browse files

Merge pull request #100 from bio-routing/feature/ip_from_string

String to BIO IP Parsing
parents b7d5aa4d 0b00897e
Branches
Tags
No related merge requests found
...@@ -62,6 +62,21 @@ func IPFromBytes(b []byte) (IP, error) { ...@@ -62,6 +62,21 @@ func IPFromBytes(b []byte) (IP, error) {
return IP{}, fmt.Errorf("byte slice has an invalid legth. Expected either 4 (IPv4) or 16 (IPv6) bytes but got: %d", len(b)) return IP{}, fmt.Errorf("byte slice has an invalid legth. Expected either 4 (IPv4) or 16 (IPv6) bytes but got: %d", len(b))
} }
// IPFromString returns an IP address for a given string
func IPFromString(str string) (IP, error) {
ip := net.ParseIP(str)
if ip == nil {
return IP{}, fmt.Errorf("%s is not a valid IP address", str)
}
ip4 := ip.To4()
if ip4 != nil {
return IPFromBytes(ip4)
}
return IPFromBytes(ip.To16())
}
// Equal returns true if ip is equal to other // Equal returns true if ip is equal to other
func (ip IP) Equal(other IP) bool { func (ip IP) Equal(other IP) bool {
return ip == other return ip == other
......
...@@ -370,3 +370,46 @@ func TestBitAtPosition(t *testing.T) { ...@@ -370,3 +370,46 @@ func TestBitAtPosition(t *testing.T) {
} }
} }
} }
func TestIPFromString(t *testing.T) {
tests := []struct {
name string
input string
expected IP
wantFail bool
}{
{
name: "ipv4",
input: "192.168.1.234",
expected: IPv4FromOctets(192, 168, 1, 234),
},
{
name: "ipv6",
input: "2001:678:1e0::cafe",
expected: IPv6FromBlocks(0x2001, 0x678, 0x1e0, 0, 0, 0, 0, 0xcafe),
},
{
name: "invalid",
input: "foo",
wantFail: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ip, err := IPFromString(test.input)
if err == nil && test.wantFail {
t.Fatal("expected error but got nil")
}
if err != nil {
if test.wantFail {
return
}
t.Fatal(err)
}
assert.Equal(t, test.expected, ip)
})
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment