IP与点分十进制数的字符串之间的转换(c++)

自己写的一个IP地址与点分十进制数的字符串之间的转换的示列:


#include "stdafx.h"
#include <iostream> 
#include <string>
//#include <windows.h> 
using namespace std; 

int IPToValue(const string& strIP)
{
//IP转化为数值
//没有格式检查
//返回值就是结果

	int a[4];
	string IP = strIP;
	string strTemp;
	size_t pos;
	size_t i=3;

	do
	{
		pos = IP.find("."); 
	
		if(pos != string::npos)
		{		
			strTemp = IP.substr(0,pos);	
			a[i] = atoi(strTemp.c_str());		
			i--;		
			IP.erase(0,pos+1);
		}
		else
		{					
			strTemp = IP;
			a[i] = atoi(strTemp.c_str());			
			break;
		}

	}while(1);

	int nResult = (a[3]<<24) + (a[2]<<16)+ (a[1]<<8) + a[0];
	return nResult;
}

string ValueToIP(const int& nValue)
{
//数值转化为IP
//没有格式检查
//返回值就是结果

	char strTemp[20];
	sprintf( strTemp,"%d.%d.%d.%d",
		(nValue&0xff000000)>>24,
		(nValue&0x00ff0000)>>16,
		(nValue&0x0000ff00)>>8,
		(nValue&0x000000ff) );

	return string(strTemp);
}

int main(void) 
{ 
	//对于218.92.189.40转化后-631456472
	//cout<<hex<<-631456472 <<endl;//输出da5cbd28

	string strIP= "218.92.189.40";
	cout<<dec<<IPToValue(strIP)<<endl;
	//cout<<hex<<IPToValue(strIP)<<endl;
	cout<<ValueToIP(-631456472)<<endl;

	//IP为:218.92.176.82转化后 -631459758 
	strIP= "218.92.176.82";
	cout<<dec<<IPToValue(strIP)<<endl;
	//cout<<hex<<IPToValue(strIP)<<endl;
	cout<<ValueToIP(-631459758)<<endl;

	return 0 ; 
} 



  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用C++中的inet_pton函数字符串IP转换为二进制形式的IP,然后再使用inet_ntoa函数将二进制形式的IP转换点分十进制形式的IP。同时,可以使用正则表达式来判断输入的字符串是否符合IP地址的格式。 下面是一个示例代码: ```c++ #include <iostream> #include <string> #include <regex> #include <arpa/inet.h> using namespace std; bool is_valid_ip(string ip_str) { regex pattern("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"); if (!regex_match(ip_str, pattern)) { return false; } struct in_addr addr; int result = inet_pton(AF_INET, ip_str.c_str(), &addr); return result != 0; } int main() { string ip_str = "192.168.0.1"; if (is_valid_ip(ip_str)) { struct in_addr addr; inet_pton(AF_INET, ip_str.c_str(), &addr); char ip[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &addr, ip, INET_ADDRSTRLEN); cout << "IP address: " << ip << endl; } else { cout << "Invalid IP address" << endl; } return 0; } ``` 在上面的示例中,is_valid_ip函数用于判断输入的字符串是否为合法的IP地址。该函数首先使用正则表达式判断输入的字符串是否符合IP地址的格式,然后使用inet_pton函数字符串IP转换为二进制形式的IP,并返回转换结果。如果返回值不为0,则表示转换成功,输入的字符串IP为合法的IP地址。 在主函数中,首先判断输入的字符串是否为合法的IP地址。如果是,则使用inet_pton和inet_ntop函数字符串IP转换点分十进制形式的IP,并输出结果;否则,输出错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值