1

Scenario: command line arguments need to be validated and converted to a socket/TCP addresses. The arguments can be any mix of IPv4 addresses, IPv6 addresses, and host-names.

Currently we're using getaddrinfo. It picks up every error I can think of except one case : a valid IPv4 address followed by some trash.

Example: "127.0.0.1 abc" (argument enclosed in quotes, so C sees a single string.).

Any suggestions on how to get around this? Is there an alternative to getaddrinfo() that detects errors more consistently? Is there some standard validation routine that should be called prior to getaddrinfo?

Or am I stuck cobbling together validations that may be incomplete?

Underhill
  • 408
  • 2
  • 13

1 Answers1

1

getaddrinfo is probably the best function to use for your purpose, but as far as I can tell, it does not guarantee to reject invalid node identifiers. I am therefore uncertain whether it's a feature or a bug that it ignores the trailing garbage in your problem case.

Nevertheless, you don't necessarily need to cobble together separate validations. Consider instead making the one you've already found stronger. For example, follow up the getaddrinfo by checking whether you can convert one of the sockaddr structures it returns back to the node identifier. getnameinfo is the complement to getaddrinfo, and it can help for the node name case. inet_ntop can help for the numerical address case (both IPv4 and IPv6, though there are additional complications in the IPv6 case). Such a procedure might also help you choose which addrinfo to use when there is more than one.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157