1. 程式人生 > >IP和整數的相互轉換

IP和整數的相互轉換

#include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
usingnamespacestd;
charstrTemp[20];
char*numbertoIp(unsignedlongnValue)
{
//staticcharszAddr[16]={0};
//unsignedlongulMask[4]={0x000000FF,0x0000FF00,0x00FF0000,0xFF000000};
//for(inti=0;i<4;i++)
//{
//longl=(ulAddr&ulMask[i])>>(i*8);
//ltoa(l,szAddr+strlen(szAddr),10);
//if(i!=3)
//strcat(szAddr,".");
//}
//returnszAddr;
//}
sprintf(strTemp,"%d.%d.%d.%d",
(nValue&0xff000000)>>24,
(nValue&0x00ff0000)>>16,
(nValue&0x0000ff00)>>8,
(nValue&0x000000ff));
std::cout<<strTemp<<endl;
returnstrTemp;
}
intmain()
{
charstr[]="244.255.213.123"
;
constchar*split=".";
char*p;
inti=0;
inta[4];
intsum=0x0;
p=strtok(str,split);
while(p!=NULL){
//printf("%s\n",p);
a[i]=atoi(p);
p=strtok(NULL,split);
//printf("%x",a[i]);
i++;
}
sum=256*256*256*a[0]+256*256*a[1]+256*a[2]+a[3];
printf("%x",sum);
numbertoIp(sum);
getchar();
return0;
}