golang检测ip,port

package main

import (
    "fmt"
    "net"
    "os/exec"
    "strconv"
    "strings"
)

func main() {

    err := CheckPorts("3306")
    if err != nil {
        fmt.Println("端口已存在")
    } else {
        fmt.Println("端口不存在")
    }
    // GetLocalIps()
}

//获取本机ip
func GetLocalIp() string {
    addrs, err := net.InterfaceAddrs()
    if err != nil {
        fmt.Println("get local ip failed")
    }
    for _, address := range addrs {
        if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
            if ipnet.IP.To4() != nil {
                return ipnet.IP.String()
            }
        }
    }
    return ""
}

//获取本机ip
func GetLocalIps() {
    interface_list, err := net.Interfaces()
    if err != nil {
        fmt.Println(err)
        return
    }
    var byName *net.Interface
    var addrList []net.Addr
    var oneAddrs []string
    for _, i := range interface_list {
        byName, err = net.InterfaceByName(i.Name)
        if err != nil {
            fmt.Println(err)
            return
        }
        addrList, err = byName.Addrs()
        if err != nil {
            fmt.Println(err)
            return
        }
        for _, oneAddr := range addrList {
            oneAddrs = strings.SplitN(oneAddr.String(), "/", 2)
            fmt.Println(i.Name, "-", oneAddrs[0])
        }
    }
}

func CheckPort(port int) error {
    checkStatement := fmt.Sprintf(`netstat -anp | grep -q %d ; echo $?`, port)
    output, err := exec.Command("sh", "-c", checkStatement).CombinedOutput()
    if err != nil {
        return err
    }
    fmt.Println(string(output))
    // log.Println(output, string(output)) ==> [48 10] 0 或 [49 10] 1
    result, err := strconv.Atoi(strings.TrimSuffix(string(output), "\n"))
    if err != nil {
        return err
    }
    if result == 0 {
        return fmt.Errorf("端口%d已被占用", port)
    }
    return nil
}

func CheckPorts(port string) error {
    var err error

    tcpAddress, err := net.ResolveTCPAddr("tcp4", ":"+port)
    if err != nil {
        return err
    }
    listener, err := net.ListenTCP("tcp", tcpAddress)
    if err != nil {
        return err
    } else {
        listener.Close()
    }

    return nil
}

你可能感兴趣的:(golang检测ip,port)