#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main()
{
char *string="192.168.10.5";
char tmp[4][4]={0};
int co[4]={0};
int i=0;
char *p,*q;
p=q=string;
while(p!=NULL)
{
p=strchr(q,'.');
if(p!=NULL)
{
strncpy(tmp[i],q,p-q);
q=p+1;
i++;
}
}
strncpy(tmp[3],q,string+strlen(string)-q);
for(i=0;i<4;i++)
{
co[i]=atoi(tmp[i]);
if(i!=3)
printf("%d.",co[i]);
else
printf("%d\n",co[i]);
}
}
提取到的整数存到int数组co中
co[0]=192
co[1]=168
co[2]=10
co[3]=5
关键代码
char *string = "192.168.10.5";
char *delims = ".";
char *byte = null;
int count = 0;
unsigned int result;
byte = strtok(string, delims);
while(byte != null){
result += atoi(byte);
if( ++count < 4)
result <<= 8;
byte = strtok(null, delims);
}
printf("result is %d\n", result);
---------------------------------------------
基本思路,用 strtok分割字节,得到的当前字节左移一个字节(8位)加上下一个字节
不想用windows api用sscanf吧,还有sprintf在转回字符串时很方便,就是效率不如自己直接写的。
int a[4];
sscanf(string, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]);
int ip = a[0]<<24|a[1]<<16]|a[2]<<8|a[3];
要另外一个顺序倒过来
使用unsigned long strIp = inet_addr(“192.168.10.5”);