Converting C++ TCP/IP applications from IPv4 to IPv6. Difficult? Worth the trouble?

前端 未结 4 2047
闹比i
闹比i 2021-01-30 14:42

Over the years I\'ve developed a small mass of C++ server/client applications for Windows using WinSock (Routers, Web/Mail/FTP Servers, etc... etc...).

I’m starting to t

4条回答
  •  借酒劲吻你
    2021-01-30 15:13

    I added IPv6 support to my previously-IPv4-only networking library about a year ago, and I didn't find it terribly difficult or traumatizing to do.

    The only big difference is how you store IP addresses :

    In IPv4 you store them as sockaddr_in's (or if you're naughty, like me, as uint32_t's).

    For IPv6 you need to store them as sockaddr_in6's (or some equivalent 128-bit structure).

    A good pre-conversion step would be to go through your code and find all of the places where IPv4 addresses are currently stored, and abstract them out into a generic IP Address class that can later be reimplemented internally to be either an IPv4 address or an IPv6 address.
    Then re-test to make sure nothing is broken in IPv4 mode... once that's checked out, you should be able to make the switch to IPv6 with just a few more changes (mainly changing PF_INET to PF_INET6, inet_aton() to inet_pton(), etc...).

    My library still ships as IPv4-only by default, but with the option of defining a preprocessor macro (-DMUSCLE_USE_IPV6) to recompile it in IPv6-aware mode.
    That way it can still be compiled on systems that don't support IPv6. One very useful feature I found along the way is IPv4-mapped IPv6 addresses: By specifying one of these (essentially an IPv4 address with 0xFFFF prepended to it), you get a socket that can talk both IPv4 and IPv6, and thus a server that can talk to both IPv4 and IPv6 clients simultaneously, without having to write separate IPv4 and IPv6 code paths for everything.

    As for whether it's worth the effort, that really depends on what you intend to do with the code. I'd say it's a good educational experience if nothing else, and it does allow your software to be used in IPv6 environments, which will become more common over time.

提交回复
热议问题