写网络程序的时候经常会用到 CString 和 DWORD 两种 IP 格式的转换,DWORD 是四个字节无符号类型,每一个字节来表示 IP 地址的点分的一位,理解了这个结构还要清楚网络字节序和本机字节序的概念,他们在内存中的表示方法刚好相反。如果你尚不清楚还请在本站搜索一下相关的关键字。下面示例程序演示了 CString 和 DWORD IP 地址的互相转换。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// CString 的 IP 转 DWORD
CString csIPAddress = _T("192.168.0.1");
DWORD dwIPAddress = 0;

// 要用到 inet_addr 函数,该函数不是安全函数
// 需要 #define _WINSOCK_DEPRECATED_NO_WARNINGS 来禁止警告
dwIPAddress = inet_addr((LPCSTR)_bstr_t(csIPAddress));

// 显示转换后的 IP
CString csConverIP;
csConverIP.Format(_T("Dec = %ld, Hex = %08X"), dwIPAddress, dwIPAddress);

MessageBox(NULL, csConverIP, NULL, NULL);

// 本地字节序转网络字节序
DWORD dwNetIPAddress = htonl(dwIPAddress);

// 格式化 CString 格式输出
csConverIP.Format(_T("%d.%d.%d.%d"),
(dwNetIPAddress >> 24) & 0xff,
(dwNetIPAddress >> 16) & 0xff,
(dwNetIPAddress >> 8) & 0xff,
dwNetIPAddress & 0xff);

MessageBox(NULL, csConverIP, NULL, NULL);