C/C++編程題之IP地址轉整數

/* 功能:將輸入的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;
}



發佈了34 篇原創文章 · 獲贊 18 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章