-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Robin
committed
Aug 26, 2020
1 parent
e374862
commit 3eba3e0
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |