Skip to content

Commit

Permalink
✨ feat: netutil - add new util func: HostIP, FreePort
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Sep 8, 2023
1 parent b6adb71 commit e884faa
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
32 changes: 28 additions & 4 deletions netutil/netutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package netutil
import (
"net"
"net/netip"
"os"
)

// InternalIPv1 get internal IP buy old logic
Expand All @@ -24,11 +25,11 @@ func InternalIPv1() (ip string) {
return
}

// GetLocalIPs get local IPs
// GetLocalIPs get local IPs, will panic if error.
func GetLocalIPs() (ips []string) {
addrs, err := net.InterfaceAddrs()
if err != nil {
panic("Oops: " + err.Error())
panic("get local IPs error: " + err.Error())
}

for _, a := range addrs {
Expand All @@ -39,7 +40,7 @@ func GetLocalIPs() (ips []string) {
return
}

// InternalIP get internal IP
// InternalIP get internal IP for host.
func InternalIP() (ip string) {
addr := netip.IPv4Unspecified()
if addr.IsValid() {
Expand All @@ -53,7 +54,7 @@ func InternalIP() (ip string) {
return ""
}

// InternalIPv4 get internal IPv4
// InternalIPv4 get internal IPv4 for host.
func InternalIPv4() (ip string) {
addr := netip.IPv4Unspecified()
if addr.IsValid() {
Expand All @@ -70,3 +71,26 @@ func InternalIPv6() (ip string) {
}
return ""
}

// HostIP returns the IP addresses of the localhost.
func HostIP() ([]string, error) {
name, err := os.Hostname()
if err != nil {
return nil, err
}

return net.LookupHost(name)
}

// FreePort returns a free port.
func FreePort() (port int, err error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err == nil {
var l *net.TCPListener
if l, err = net.ListenTCP("tcp", addr); err == nil {
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
}
return
}
20 changes: 20 additions & 0 deletions netutil/netutil_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package netutil_test

import (
"fmt"
"testing"

"github.com/gookit/goutil/netutil"
Expand All @@ -14,3 +15,22 @@ func TestInternalIP(t *testing.T) {
assert.NotEmpty(t, netutil.InternalIPv6())
assert.NotEmpty(t, netutil.GetLocalIPs())
}

func TestHostIP(t *testing.T) {
addrs, err := netutil.HostIP()
if err != nil {
t.Skip("skip test for error: " + err.Error())
return
}

assert.NoError(t, err)
assert.NotEmpty(t, addrs)
fmt.Println(addrs)
}

func TestFreePort(t *testing.T) {
port, err := netutil.FreePort()
assert.NoError(t, err)
assert.Gt(t, port, 0)
assert.Lt(t, port, 65536)
}

0 comments on commit e884faa

Please sign in to comment.