From 954f4443f679162d7e2dbc36daee8795ae71ed9e Mon Sep 17 00:00:00 2001 From: Paul Holzinger Date: Mon, 11 Apr 2022 14:45:25 +0200 Subject: [PATCH] libnetwork/util: add GetNetworkIPs() Add helper function to get the first ipv4 and ipv6 from the network status. Since this is stored as a map, calling this function multiple times is not deterministic. The caller (Podman) should store this result to make sure it will keep using the same ips. Signed-off-by: Paul Holzinger --- libnetwork/util/ip.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/libnetwork/util/ip.go b/libnetwork/util/ip.go index 7c315e312..47ba68e12 100644 --- a/libnetwork/util/ip.go +++ b/libnetwork/util/ip.go @@ -2,6 +2,8 @@ package util import ( "net" + + "github.com/containers/common/libnetwork/types" ) // IsIPv6 returns true if netIP is IPv6. @@ -54,3 +56,27 @@ func NormalizeIP(ip *net.IP) { *ip = ipv4 } } + +// GetNetworkIPs return one ipv4 and ipv6 address of this network status. +// The first return value is the ipv4 and the second one the ipv6 address. +// If there is no ipv4/6 address it will return an empty string instead. +func GetNetworkIPs(netStatus map[string]types.StatusBlock) (ipv4, ipv6 string) { + for _, status := range netStatus { + for _, netInt := range status.Interfaces { + for _, netAddress := range netInt.Subnets { + if IsIPv4(netAddress.IPNet.IP) { + if ipv4 == "" { + ipv4 = netAddress.IPNet.IP.String() + } + } else if ipv6 == "" { + ipv6 = netAddress.IPNet.IP.String() + } + + if ipv4 != "" && ipv6 != "" { + return ipv4, ipv6 + } + } + } + } + return ipv4, ipv6 +}