Skip to content

net/netip: ParseAddr should reject invalid zone #71362

Open
@qinlonglong123

Description

@qinlonglong123

Proposal Details

I have the following use case:

package main

import (
    "fmt"
    "net/netip"
)

func main() {
    addr, err := netip.ParseAddr("2006:abcd::1%%")
    fmt.Printf("addr = %s,zone = %s,err = %v\n", addr.String(), addr.Zone(), err)
}

https://go.dev/play/p/soSl7hzPhJx
output:

addr = 2006:abcd::1%%,zone = %,err = <nil>

When running with Go 1.23, it considers the last % as the IPv6 zone ID. However, when parsing the same address in other languages, it considers the parameter as an invalid IP, for example:

1.C Language

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>

const char* parse_ipv6_with_zone_id(const char *input) {
    struct addrinfo hints, *res;
    int status;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET6;
    hints.ai_socktype = SOCK_STREAM;

    status = getaddrinfo(input, NULL, &hints, &res);

    if (status != 0) {
        return "Invalid";
    }

    freeaddrinfo(res);
    return "Valid";
}

int main() {
    const char *input1 = "2006:abcd::1%%";

    printf("Address 1: %s - %s\n", input1, parse_ipv6_with_zone_id(input1));

    return 0;
}

gcc version

gcc version 10.3.1 (GCC)

and output:

Address 1: 2006:abcd::1%% - Invalid

2. java

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;

public class IPv6ZoneIDParser {
 public static void main(String[] args) {
        final String ipv6WithZone = "2006:abcd::1%%";
        try {
            InetAddress inetAddress = InetAddress.getByName(ipv6WithZone);
            if (inetAddress instanceof Inet6Address) {
                System.out.println(ipv6WithZone + " It is an IPv6 address.");
            }

        } catch (java.net.UnknownHostException e) {
            System.out.println(ipv6WithZone + " It is a invalid ip address.");
        }
    }
}

java -version
openjdk version "1.8.0_392"

output:
2006:abcd::1%% It is a invalid ip address.

3. python

import ipaddress

def is_valid_ip(ip):
    try:
        ipaddress.ip_address(ip)
        return True
    except ValueError:
        return False

print(is_valid_ip("2006:abcd::1%%"))

python version
Python 3.9.11 (main, Jul 18 2024, 15:21:06)

output:
False

why Go language behaves differently when parsing IPv6 zone IDs compared to other languages as shown above? Thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugReportIssues describing a possible bug in the Go implementation.NeedsDecisionFeedback is required from experts, contributors, and/or the community before a change can be made.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions