1.use strtok()
2.shift by bit-computing位运算
char a[]="1.0.0.1";
char *p=NULL;
char *d=".";
p=strtok(a,d);
while(p){
cout<<p;
p=strtok(NULL,d);
}2.shift by bit-computing位运算
//input a CONST IP String,return a 32-bit integer
#include "stdafx.h"
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
using namespace std;
int ipstr2int(const char*ip){
int result = 0;
int tmp = 0;
int shift = 24;
const char*pEnd = ip;
const char*pStart = ip;
while(*pEnd!='\0'){
while(*pEnd!='.'&&*pEnd!='\0'){//find out the "." in IP String
pEnd++;
}
tmp=0;
while(pStart<pEnd){//calculate the value divided by '.'
tmp=tmp*10+(*pStart-'0');
pStart++;
}
//shift for 24.16.8.0 of each segment
result+=(tmp<<shift);
shift-=8;
if(*pEnd=='\0')
break;
pStart=pEnd+1;
pEnd++;
}
return result;
}
int main()
{
char*a="1.0.0.1";
cout<<"IP:"<<endl;
cout<<"int:"<<ipstr2int(a)<<endl;;
}
本文介绍了两种将IP地址转换为32位整数的方法:使用strtok()函数分割IP地址,并通过位运算进行转换。这两种方法适用于网络编程中IP地址的处理。
2444

被折叠的 条评论
为什么被折叠?



