IP地址转换为unsigned int,unsigned int 转换成IP地址

ip地址转换为unsigned int 方法:

例如ip地址“192.168.0.112”,四部分分别转换成整型的数t[4](利用atoi函数),转换后的数即为t[0]*(256^3)+t[1]*(256^2)+t[2]*256+t[3];

unsigned int 转换成ip地址方法:

定义联合体

union IP 
{
    unsigned char char_ip[4];
    unsigned int uint_ip; 
};

将整型数存入联合体中,利用char_ip[4]得出ip地址(利用itoa函数)

#include<iostream>
using namespace std;
 
union IP 
{
	unsigned char char_ip[4];
	unsigned int uint_ip; 
};
unsigned int IptoUint(char * ip,int size)
{
	unsigned int t[4]; 
	int dot_ind[3]={0};//存储.位置
	int j=0;
	for(int i=0;i<size;i++)
	{
		if(ip[i]=='.')
		{
			dot_ind[j++]=i;
		}
	}
	char *p=(char *)malloc(3);
	p=strncpy (p,ip,dot_ind[0]);
	t[0]=atoi(p);
	p=strncpy (p,ip+dot_ind[0]+1,dot_ind[1]-dot_ind[0]-1);
	t[1]=atoi(p);
	p=strncpy (p,ip+dot_ind[1]+1,dot_ind[2]-dot_ind[1]-1);
	t[2]=atoi(p);
	p=strncpy (p,ip+dot_ind[2]+1,size-dot_ind[2]-1);
	t[3]=atoi(p);
	unsigned int ip_uint=t[0]*256*256*256+t[1]*256*256+t[2]*256+t[3];
	return ip_uint;
}
 
char* UinttoIp(const unsigned int a)
{
	IP ip;
	ip.uint_ip=a;
	char * pp=new char[20];
	memset(pp,0,20);
 
	for(int i=3;i>=0;i--)//由机器的大小端决定,此处是小端,即高位存在高地址,地位存在低地址
	{
 
		char tmp[4]="";
		itoa(ip.char_ip[i],tmp,10);
		strcat(pp,tmp);
		if(i>0)
		{
			char *dot=".";
			strcat(pp,dot);
		}
	}
	return pp;
 
}
 
int main()
{
	char s[20]="";//"255.255.255.255";
	cout<<"请输入ip地址:";
	cin>>s;
	cout<<"您输入的ip地址是:"<<s<<endl;
	unsigned int b=IptoUint(s,strlen(s));
	cout<<"转换成uint字符是:"<<b<<endl;
	
	cout<<"uint再转换为ip地址是:"<<UinttoIp(b)<<endl;  
    return 0; 
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值