Subject: does getaddrinfo() behave correctly?
To: None <tech-userlevel@NetBSD.org>
From: Klaus Heinz <k.heinz.sep.sieben@kh-22.de>
List: tech-userlevel
Date: 09/16/2007 00:07:30
Hi,

in the course of building a package I discovered this (IMO) strange
behaviour of getaddrinfo() concerning port numbers:

  #include <stdio.h>
  #include <netdb.h>
  #include <string.h>

  int
  main(int argc, char * argv[]) {

    const char* hostname = argv[1];
    const char* servname = argv[2];
    struct addrinfo * res = (struct addrinfo *) malloc(sizeof(struct addrinfo));

    if (res) {
      (void) memset(res, 0, sizeof(struct addrinfo));

      int rc = getaddrinfo(hostname, servname, 0, &res);
      printf ("result: %d = %s\n", rc, gai_strerror(rc));

      if (!rc) {
        printf("flags: %d, family: %d, socktype: %d, protocol: %d\n", res->ai_flags, res->ai_family, res->ai_socktype, res->ai_protocol);
        freeaddrinfo(res);
      }
    } else {
      fprintf(stderr, "could not allocate addrinfo\n");
    }
  }

This works as expected:
  $ ./test-getaddrinfo localhost smtp
  result: 0 = Success
  flags: 0, family: 24, socktype: 1, protocol: 6
  $ ./test-getaddrinfo 127.0.0.1 smtp
  result: 0 = Success
  flags: 0, family: 2, socktype: 1, protocol: 6

This does not:
  $ ./test-getaddrinfo localhost 25  
  result: 9 = servname not supported for ai_socktype
  $ ./test-getaddrinfo 127.0.0.1 25
  result: 9 = servname not supported for ai_socktype

The man page getaddrinfo(3) from NetBSD 3.0 and RFC 3493 at
  ftp://ftp.rfc-editor.org/in-notes/rfc3493.txt
say explicitly that "servname" can be a decimal number string.

I also made this test on a Linux box (Debian Sarge) and strangely
enough I see the same behaviour:

  $ ./test-getaddrinfo localhost smtp
  result: 0 = Unknown error
  flags: 40, family: 2, socktype: 1, protocol: 6
  $ ./test-getaddrinfo 127.0.0.1 smtp
  result: 0 = Unknown error
  flags: 40, family: 2, socktype: 1, protocol: 6

  $ ./test-getaddrinfo localhost 25
  result: -8 = Servname not supported for ai_socktype
  $ ./test-getaddrinfo 127.0.0.1 25
  result: -8 = Servname not supported for ai_socktype 

What am I missing?

ciao
     Klaus