1. 程式人生 > >C/C++程式設計題之IP地址轉整數

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;
}