-
-
Save seanrclayton/89528b17a655663eb167253ae9a32fce to your computer and use it in GitHub Desktop.
[golang] get specific network interface's IPv4 address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment