Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I want to convert IpAddress to dword variable...

char IpAddress[4]; // means 255.255.255.255
DWORD dwIPAddress;
CString CstringIP = _T("");

CstringIP.Format("%u%u%u%u",IpAddress[0],IpAddress[1], IpAddress[2], IpAddress[3]);

So I get the CString IP Address from IpAddress values.

But next,
I have no idea this CstringIP to dwIPAddress.
Who know the method ?

or
Any other easier method?

What I have tried:

3 more hours wasted on this problem...
Posted
Updated 19-Mar-16 23:38pm

In theory, you can just cast it - but that's risky, because a char array or char pointer doesn't have to be aligned to an address boundary, and a DWORD does. And you shouldn't use char anyway, as it's a signed value - you really want byte instead.
So I'd do this:
C++
DWORD DwordFromBytes(byte *b)
    {
    return (b[0]) | (b[1] << 8) | (b[2] << 16) | (b[3] << 24);
    }
 
Share this answer
 
You must parse the string to get the four elements, convert these to numbers, and combine the numbers to a DWORD (assuming an IPv4 address in dotted notation; your CString.Format example misses the periods in it).

There are various methods to perform the parsing:

Using sscanf, _sscanf_l, swscanf, _swscanf_l[^]


C++
unsigned bytes[4];
int fields = _stscanf(str.GetString(), _T("%u.%u.%u.%u"), 
    bytes+3, bytes+2, bytes+1, bytes);
// Error check: Valid if fields == 4 and all bytes[] values are valid (< 256)

Using strtoul, _strtoul_l, wcstoul, _wcstoul_l[^]


C++
unsigned long bytes[4];
LPCTSTR parse = str.GetString();
LPTSTR endptr;
int i;
for (i = 3; parse != NULL && i >= 0; i--)
{
    bytes[i] = _tcstoul(parse, &endptr, 10);
    // endptr points to the character that stops the conversion
    // When this is a period, resume at the character behind it
    if (*endptr == _T('.'))
        parse = endptr + 1;
    else
        parse = NULL;
}
// Error check: Valid if i < 0 and all bytes[] values are valid (< 256)


Besides the above examples there are more functions that can be used to parse the string like CStringT::Tokenize[^] and regular expressions (<regex>[^]).

Finally combine the four numbers to a DWORD:
C++
DWORD dwIP = bytes[0] + (bytes[1] << 8) + (bytes[2] << 16) + (bytes[3] << 24);
 
Share this answer
 
Comments
Arthur V. Ratz 21-Mar-16 2:42am    
Good answer. +5

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