C/C++编程题之IP地址转整数

来源:互联网 发布:施工现场平面图 软件 编辑:程序博客网 时间:2024/05/16 17:00
/* 功能:将输入的string类型的IP信息转换为string类型
 * 输入:string类型的IP信息
 * 输出:DWORD结果,正常返回解析结果值,异常时,dwIP为0
 * 返回:返回解析的整型,异常时返回"0"

 */

代码:

#include <stdlib.h>#include <atlstr.h>#include "oj.h"#include <iostream>#include <string>using namespace std;bool effective(string strIP)//检查ip地址的有效性{int cnt = 0;char *ip = (char*)strIP.c_str();while(*ip != '\0'){if(*ip == '.'){cnt++;}if(*ip >= '0' && *ip <= '9' || *ip == '.'){ip++;}else{return false;}}if(cnt != 3)return false;return true;}string GetValueByIP(string strIP){if(!effective(strIP))return "0";unsigned int res = 0;char resIp[12] = {0};unsigned char value[4] = {0};//存放IP地址的四个数字char word[10] = {0};int cnt = 0,cntNum = 0;char *ip = (char*)strIP.c_str();while(*ip != '\0')//拆分到value{while(*ip != '\0' && *ip != '.'){word[cnt++] = *ip;ip++;}word[cnt] = '\0';cnt = 0;if(atoi(word) > 255 || atoi(word) < 0)return "0";value[cntNum++] = atoi(word);if(cntNum == 4)break;ip++;}res = (value[0]<<24) | (value[1]<<16) | (value[2]<<8) | value[3];//将四个数字进行拼接成一个整数sprintf_s(resIp,sizeof(resIp),"%u\0",res);string result = resIp;return result;}



0 0
原创粉丝点击