Skip to content

Commit

Permalink
add local ip util
Browse files Browse the repository at this point in the history
  • Loading branch information
Robin committed Aug 26, 2020
1 parent e374862 commit 3eba3e0
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
42 changes: 42 additions & 0 deletions network/ips.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package network

import "net"

func GetLocalIps() ([]string, error) {
ips := make([]string, 0)
ifaces, err := net.Interfaces()
if err != nil {
return ips, err
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
return ips, err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
ips = append(ips, ip.String())
}
}
return ips, nil
}

func IsLocalIp(ip string) (bool, error) {
isLocal := false
ips, err := GetLocalIps()
if err != nil {
return isLocal, err
}
for _, item := range ips {
if item == ip {
return true, nil
}
}
return isLocal, nil
}
14 changes: 14 additions & 0 deletions network/ips_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package network

import (
"github.com/stretchr/testify/assert"
"testing"
)

func TestIsLocalIp(t *testing.T) {
isLocal, err := IsLocalIp("127.0.0.1")
if err != nil {
t.Fatal(err)
}
assert.True(t, isLocal)
}

0 comments on commit 3eba3e0

Please sign in to comment.