How to get ip from ifconfig by broadcast addess?

Viewed 31

I have broadcast address in config for udp packages.

How to get ip address in server ( from ifconfig info interfaces ) by broadcast address ?

1 Answers

Does this code solve your problem ?

import (
    "net"

    "github.com/pkg/errors"
)

func IpAddr() (string, error) {
    addrs, err := net.InterfaceAddrs()

    if err != nil {
        return "", err
    }

    for _, addr := range addrs {
        if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
            if ipnet.IP.To4() != nil {
                return ipnet.IP.String(), nil
            }
        }
    }
    return "", errors.New("unable to determine local ip")
}
Related