[swift-users] POSIX getaddrinfo memory behaviour
Quinn "The Eskimo!"
eskimo1 at apple.com
Tue Oct 4 12:18:59 CDT 2016
On 4 Oct 2016, at 17:46, Etan Kissling via swift-users <swift-users at swift.org> wrote:
> I don't feel that the function is correct
It’s definitely not correct. The problem is that each `addrinfo` structure in your function has pointers to memory that’s freed by the `freeaddrinfo()` call.
You have a bunch of options here:
A. avoid `getaddrinfo` — The POSIX ‘resolve then connect’ approach is deeply painful when dealing with the random mix of IPv4 and IPv6 addresses you find in the real world. I strongly recommend that you use a connect-by-name API instead, like CFSocketStream (which you access via `Stream.getStreamsToHost(withName:port:inputStream:outputStream:)`).
The only reason /not/ to do this is if you’re using the address list for something other than opening a TCP connection.
Even if you back end is BSD Sockets, you can extract the file descriptor from the stream once it’s connected.
B. capture the addresses referenced by each `addrinfo`
C. wrap the address list in a class that holds it in memory while you access it
All of these options work but, realistically, A is the easiest and the best.
Share and Enjoy
--
Quinn "The Eskimo!" <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
More information about the swift-users
mailing list