Skip to content

Instantly share code, notes, and snippets.

@schwarzeni
Last active July 3, 2024 21:50
Show Gist options
  • Save schwarzeni/f25031a3123f895ff3785970921e962c to your computer and use it in GitHub Desktop.
Save schwarzeni/f25031a3123f895ff3785970921e962c to your computer and use it in GitHub Desktop.
[golang] get specific network interface's IPv4 address
package util
import (
"errors"
"fmt"
"net"
)
// useful links:
// https://stackoverflow.com/questions/27410764/dial-with-a-specific-address-interface-golang
// https://stackoverflow.com/questions/22751035/golang-distinguish-ipv4-ipv6
func GetInterfaceIpv4Addr(interfaceName string) (addr string, err error) {
var (
ief *net.Interface
addrs []net.Addr
ipv4Addr net.IP
)
if ief, err = net.InterfaceByName(interfaceName); err != nil { // get interface
return
}
if addrs, err = ief.Addrs(); err != nil { // get addresses
return
}
for _, addr := range addrs { // get ipv4 address
if ipv4Addr = addr.(*net.IPNet).IP.To4(); ipv4Addr != nil {
break
}
}
if ipv4Addr == nil {
return "", errors.New(fmt.Sprintf("interface %s don't have an ipv4 address\n", interfaceName))
}
return ipv4Addr.String(), nil
}
@joonas-fi
Copy link

Thanks! ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment