IP地址字符串和DWORD互转(VC)

2015-08-12 19:27:10来源:作者:人点击

IP地址字符串和DWORD互转(VC),有需要的朋友可以参考下。


转自:http://blog.sina.com.cn/s/blog_7d0544020100xjd7.html
#include <windows.h>
BOOL StrAddr2Dword(CHAR* lpStrAddr, DWORD* pdwAddr){char* lpPos = lpStrAddr; //指向当前操作的字符int nNumCount = 0; //数字的个数int nPointCount = 0; //分隔点的个数BOOL bResult = FALSE; //函数是否执行成功DWORD dwAddr = 0;DWORD Temp = 0;
//进行参数的有效性检查if (!lpStrAddr || !pdwAddr){return bResult;}
while (*lpPos && nPointCount < 4){if (nNumCount < 3){if (*lpPos >= 0x30 && *lpPos <= 0x39){bResult = TRUE;dwAddr -= Temp; Temp *= 10;Temp += (*lpPos - 0x30);if (Temp & ~0xFF){break; //从这里退出说明单个数超过了255,}dwAddr += Temp;nNumCount++;}else if (*lpPos != '.'){break; //从这里退出说明有非数字的字符}else{if (!nNumCount){break; //从这里退出说明单个数超过了255,或者是在一个分组中第个字符为点}else{bResult = FALSE;Temp = 0;dwAddr <<= 8;nNumCount = 0;nPointCount++;}}}else{if (*lpPos != '.'){break; //单组数字字符超过了3个}else{bResult = FALSE;Temp = 0;dwAddr <<= 8;nNumCount = 0;nPointCount++;}}lpPos++;}
//凡是通过break跳出来的*lpPos肯定不为空。//bResult为假说明点以后再没取到字符。if (!(*lpPos) && nPointCount == 3 && bResult){*pdwAddr = dwAddr;}else{bResult = FALSE;}
return bResult;}

BOOL DwordAddr2Str(DWORD dwAddr, CHAR* lpStrAddr){DWORD Fmt = 0xFF << 24; //该运算为常量运算编译器会做优化DWORD Temp = 0;CHAR Number = 0;if (!lpStrAddr){return FALSE;}
for (int i = 3; i >= 0; i--){Temp = dwAddr & Fmt;Temp >>= 8*i;Number = (BYTE)Temp/100;if (Number != 0){*lpStrAddr = Number + '0';lpStrAddr++;}
Number = ((BYTE)Temp/10) % 10;if (Number != 0){*lpStrAddr = Number + '0';lpStrAddr++;}
Number = (BYTE)Temp;*lpStrAddr = Number + '0';lpStrAddr++;
if (i > 0){*lpStrAddr = '.';lpStrAddr++;}
Fmt >>= 8;}
return TRUE;}
//000.000.000.000是有效的IP//0000.0000.0000.0000是无效的IP//单组长度只支持到3位。int _tmain(int argc, _TCHAR* argv[]){DWORD addr = 0;static char Buffer[1024*1024];
do{printf("请输入一个字符串形式的IP地址进行计算:");scanf("%s", Buffer);if (StrAddr2Dword(Buffer, &addr)){printf("/r/n%s = X/r/n", Buffer, addr);memset(Buffer, 0, sizeof(Buffer));printf("再次转回去/r/n");if (DwordAddr2Str(addr,Buffer)){printf("X = %s/r/n", addr, Buffer);}else{printf("转换失败!/r/n");}}else{printf("/r/n%s是无效的IP地址!/r/n", Buffer);}} while (TRUE);return 0;}

微信扫一扫

第七城市微信公众平台