From 761d7eb4217933c96d0f7e77e13bd1c2c9ec2cc0 Mon Sep 17 00:00:00 2001 From: Hayato Kiwata Date: Sun, 13 Sep 2026 22:16:00 +0900 Subject: [PATCH] refactor: use `netip.Addr.Next()` instead of `math/big` in `AddIPInt6` follow-up: https://github.com/rootless-containers/rootlesskit/pull/620#discussion_r3957446613 Signed-off-by: Hayato Kiwata --- pkg/network/iputils/iputils.go | 22 ++++++++++++++-------- pkg/network/iputils/iputils_test.go | 5 +++++ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/pkg/network/iputils/iputils.go b/pkg/network/iputils/iputils.go index d200018d..616b5a24 100644 --- a/pkg/network/iputils/iputils.go +++ b/pkg/network/iputils/iputils.go @@ -4,8 +4,8 @@ import ( "encoding/binary" "fmt" "math" - "math/big" "net" + "net/netip" ) func AddIPInt(ip net.IP, i int) (net.IP, error) { @@ -28,12 +28,18 @@ func AddIPInt6(ip net.IP, i int) (net.IP, error) { if ip.To4() != nil || ip6 == nil { return nil, fmt.Errorf("expected IPv6 address, got %s", ip.String()) } - b := new(big.Int).SetBytes(ip6) - b.Add(b, big.NewInt(int64(i))) - if b.Sign() < 0 || b.BitLen() > 128 { - return nil, fmt.Errorf("%s + %d overflows", ip.String(), i) + if i < 0 { + return nil, fmt.Errorf("expected non-negative integer, got %d", i) } - res := make(net.IP, net.IPv6len) - b.FillBytes(res) - return res, nil + addr, ok := netip.AddrFromSlice(ip6) + if !ok { + return nil, fmt.Errorf("expected IPv6 address, got %s", ip.String()) + } + for n := 0; n < i; n++ { + addr = addr.Next() + if !addr.IsValid() { + return nil, fmt.Errorf("%s + %d overflows", ip.String(), i) + } + } + return net.IP(addr.AsSlice()), nil } diff --git a/pkg/network/iputils/iputils_test.go b/pkg/network/iputils/iputils_test.go index 8d6ae79d..b54ca5d8 100644 --- a/pkg/network/iputils/iputils_test.go +++ b/pkg/network/iputils/iputils_test.go @@ -72,6 +72,11 @@ func TestAddIPInt6(t *testing.T) { 0x1, "fd00::1:0", }, + { + "fd00::ffff", + -1, + "", + }, { "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0x1,