Search code examples
c++winsockwinsock2

inet_ntoa() in Winsock2 is deprecated?


I was experimenting with Winsock2 at the moment, and got a warning that inet_ntoa() is deprecated and that I should use inet_pton(). I tried it, but it was little endian, so the whole string that was saved in the buffer was "wrong". I'm guessing inet_ntoa() is big endian?

And I could only use inet_pton() with #include <ws2tcpip.h>, so for me it just gets more confusing from here on. Why should I use something else outside the <winsock2.h> library?

Currently, I'm avoiding this by using #pragma warning(disable : 4996), which I don't like, because I just don't want to ignore all warnings.

This whole Winsock topic is like a maze for me, sorry if I'm missing some information, hope that's enough.


Solution

  • inet_pton() is NOT the successor for inet_ntoa(), but for inet_addr() instead. You want inet_ntop() instead.

    inet_ntoa()/inet_ntop() convert an IP address from binary form to string form. inet_addr()/inet_pton() do the opposite conversion.

    However, there are actually several functions that you can use instead of inet_ntoa(), including getnameinfo(), WSAAddressToString(), RtlIpv4AddressToString()/RtlIpv6AddressToString(), etc.

    That being said, yes inet_ntoa() is indeed deprecated, because it only support IPv4 addresses. Functions like inet_ntop(), getnameinfo(), etc support both IPv4 and IPv6 addresses, which makes writing IP version-agnostic code a bit easier.

    If you are having trouble with inet_ntop() then you are using it wrong, but you did not show your code. IPv4 addresses are always expressed in binary form in "network byte order" (big endian), even on little endian systems, like Windows.

    As for <ws2tcpip.h>, that is part of the Winsock2 library. Nothing requires an API to only have 1 header file (indeed, the Win32 API as a whole consists of thousands of header files, beginning with but not limited to <windows.h>).

    The correct way to deal with the deprecation warning is to update your code to use a modern API that is not deprecated, like it wants you to. Otherwise, if that is not an option for you at this time, then at the very least you can use #pragma warning(suppress : 4996) on just the affected code, rather than use #pragma warning(disable : 4996) globally. Or, you can define _WINSOCK_DEPRECATED_NO_WARNINGS in your project setup, or you can #define it in your code before #include'ing any Winsock2 headers.