Calling BSD Sockets from Swift

This thread has been locked by a moderator; it no longer accepts new replies.

I find myself using BSD Sockets a lot. Ironically this isn’t because I’m doing networking. If I’m writing networking code on Apple platforms, I use one of Apple’s preferred APIs, like URLSession or Network framework. For more on this see TN3151 Choosing the right networking API

No, I’m using BSD Sockets tangentially, not for my core networking code but for other, weirder stuff. For example, I might want to get a list of all the IP addresses on the system, and that requires calling getifaddrs, which returns its results as struct sockaddr values, which is the BSD Sockets address primitive.

Calling BSD Sockets correctly from Swift is a challenge [1]. Over the years I’ve come up with numerous wrappers to make this easier. I’ve found that tricky to do. If I were writing production code I would create a comprehensive wrapper that covers all the details. However, I don’t write production code, I write test projects, snippets for posting to DevForums, and so on. Given that, I want my wrapper to be thin, so that the reader can understand the BSD Sockets concepts without getting lost of the wrapper.

Oh, and I don’t really care about efficiency (-:

Recently I’ve used my understanding of these goals to create a BSD Sockets wrapper that I’m comfortable sharing. It’s convenient, reasonably ‘thin’, and works well for test projects, snippets, and so on.

It can also be wildly inefficient but, as mentioned above, I don’t care about that (-:

IMPORTANT TN3151 discusses the circumstances under which it makes sense to use BSD Sockets for networking. Most of these involve calling BSD Sockets from a C-based language rather than Swift, and my wrapper is irrelevant in that case.

So, with that out of the way, meet QSocket2023! [2]

Well… actually… I’m going to put this in four separate posts:

Finally, if you’re using BSD Sockets for networking, you might be interested in Monitoring Socket Viability.

If you have any questions or comments about this stuff, please start a new thread here on DevForums. Tag it with Network so that I see it.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] Rumour has it that, even in C, calling BSD Sockets without bumping into undefined behaviour is a challenge, but I’ll let the C language lawyers litigate that (-:

[2] That’s right, I’ve written so many BSD Sockets wrappers that I’ve started using the year to distinguish them!

Revision History

Boost
Calling BSD Sockets from Swift
 
 
Q