diff --git a/net_freebsd.go b/net_freebsd.go index ea0955e..ea74118 100644 --- a/net_freebsd.go +++ b/net_freebsd.go @@ -9,3 +9,20 @@ package main func setupPortForward(ip, port string) { } + +func portUsageCount(ports ...[]int) int { + const CMD = "sockstat -4c -p 22" + return 0 +} + +func portUsageCount(ports ...int) int { + cmd := "sockstat -4c" + for _, v := range ports { + cmd += " -p " + strconv.Itoa(v) + } + out, err := exec.Command(cmd).Output() + if err != nil { + log.Println("Port Usage Check: Could not run ", cmd) + } + return bytes.Count(out, []byte{'\n'}) - 1 +} diff --git a/net_linux.go b/net_linux.go index e7980b1..eed00cf 100644 --- a/net_linux.go +++ b/net_linux.go @@ -8,10 +8,25 @@ package main import ( + "bytes" "log" + "os/exec" + "strconv" ) // just have this stub to allow building on Linux func setupPortForward(ip, port string) { log.Print("Port forwarding not currently implemented for Linux/iptables") } + +func portUsageCount(ports ...int) int { + cmd := "sockstat -4c" + for _, v := range ports { + cmd += " -p " + strconv.Itoa(v) + } + out, err := exec.Command(cmd).Output() + if err != nil { + log.Println("Port Usage Check: Could not run ", cmd) + } + return bytes.Count(out, []byte{'\n'}) - 1 +} diff --git a/net_test.go b/net_test.go new file mode 100644 index 0000000..51ba338 --- /dev/null +++ b/net_test.go @@ -0,0 +1,27 @@ +/* + Copyright 2016 gtalent2@gmail.com + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ +package main + +import ( + "net" + "strconv" + "testing" +) + +func TestPortCount(t *testing.T) { + port := 49214 + // listen on some port that nothing should be using for the sake of the test + go func() { + addr, _ := net.ResolveTCPAddr("tcp", "0.0.0.0:"+strconv.Itoa(port)) + net.ListenTCP("tcp", addr) + }() + + if portUsageCount(49214) != 1 { + t.Errorf("Port count usage reporting wrong number") + } +}