A simple method would be using
CStringT::Format[
^]:
CString str;
str.Format(_T("%u.%u.%u.%u"),
(unsigned char)ipaddr[3], (unsigned char)ipaddr[2],
(unsigned char)ipaddr[1], (unsigned char)ipaddr[0]);
Note the casting to
unsigned char
. It tells the compiler to treat the
signed char
as unsigned to avoid negative numbers for values greater than 127. Note also that the above assumes the lowest address part to be in
ipaddr[0]
. If it is the other way, adjust the indexes.
A more portable way of getting a string from an IP address is using the
inet_ntoa function (Windows)[
^] (include
winsock2.h and link with
ws2_32.lib). But this requires copying the IP address to an
in_addr structure (Windows)[
^] and converting the returned ANSI string:
# pragma comment(lib, "ws2_32")
struct in_addr addr;
addr.S_un.S_un_b.s_b1 = ipaddr[0];
addr.S_un.S_un_b.s_b2 = ipaddr[1];
addr.S_un.S_un_b.s_b3 = ipaddr[2];
addr.S_un.S_un_b.s_b4 = ipaddr[3];
CString strIP(inet_ntoa(addr));