Skip to content

Commit

Permalink
Merge pull request containers#1504 from Luap99/GetLocalIP
Browse files Browse the repository at this point in the history
libnetwork/util: export GetLocalIP()
  • Loading branch information
openshift-merge-robot authored Jun 15, 2023
2 parents 86bfdb3 + de4006e commit 2d3d680
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 24 deletions.
26 changes: 2 additions & 24 deletions libnetwork/etchosts/ip.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package etchosts

import (
"net"

"github.com/containers/common/libnetwork/types"
"github.com/containers/common/libnetwork/util"
"github.com/containers/common/pkg/config"
Expand All @@ -29,7 +27,7 @@ func GetHostContainersInternalIP(conf *config.Config, netStatus map[string]types
// Only use the bridge ip when root, as rootless the interfaces are created
// inside the special netns and not the host so we cannot use them.
if unshare.IsRootless() {
return getLocalIP()
return util.GetLocalIP()
}
for net, status := range netStatus {
network, err := networkInterface.NetworkInspect(net)
Expand All @@ -53,27 +51,7 @@ func GetHostContainersInternalIP(conf *config.Config, netStatus map[string]types
if ip != "" {
return ip
}
return getLocalIP()
}

// getLocalIP returns the non loopback local IP of the host
func getLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
ip := ""
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && ipnet.IP.IsGlobalUnicast() {
if util.IsIPv4(ipnet.IP) {
return ipnet.IP.String()
}
// if ipv6 we keep looking for an ipv4 address
ip = ipnet.IP.String()
}
}
return ip
return util.GetLocalIP()
}

// GetNetworkHostEntries returns HostEntries for all ips in the network status
Expand Down
22 changes: 22 additions & 0 deletions libnetwork/util/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,25 @@ func NormalizeIP(ip *net.IP) {
*ip = ipv4
}
}

// GetLocalIP returns the first non loopback local IPv4 of the host.
// If no ipv4 address is found it may return an ipv6 address.
// When no ip is found and empty string is returned.
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
ip := ""
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && ipnet.IP.IsGlobalUnicast() {
if IsIPv4(ipnet.IP) {
return ipnet.IP.String()
}
// if ipv6 we keep looking for an ipv4 address
ip = ipnet.IP.String()
}
}
return ip
}

0 comments on commit 2d3d680

Please sign in to comment.