Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to know how to convert ipaddr variable to CString.

1. char ipaddr[4];
This means that ipaddr has 4 numbers like xxx.xxx.xxx.xxx (xxx: 0~255)

2. So I wanna to convert this value to CString so display in the Screen using MFC.

I am appreciate if any help me.

Thank you.

What I have tried:

Because I am a novice to C++. So I am very hardful of it.
Posted
Updated 15-Mar-16 23:41pm

1 solution

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:
C++
//#include "winsock2.h" // Include in stdafx.h 
# 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)); 
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900