IP解析
IP地址ascii码转16进制。在单片机的环境下,很多时候显示都是ASCII码,当在使用的过程中一般习惯性的将IP地址存入到16进制的数据中。本文主要记录解析IP地址的方法。
使用语言C语言
主要使用到C语言库#include <stdlib.h>库。
主要库函数使用
1.strchr
C 库函数 char *strchr(const char *str, int c) 在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置。
char *strchr(const char *str, int c)
参数
str – 要被检索的 C 字符串。
c – 在 str 中要搜索的字符。
C 库函数 int atoi(const char *str) 把参数 str 所指向的字符串转换为一个整数(类型为 int 型)。
2.atoi()
atoi() 函数用来将字符串转换成整数(int),其原型为:
int atoi (const char * str);
atoi() 函数会扫描参数 str 字符串,跳过前面的空白字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时(’\0’)才结束转换,并将结果返回。
str – 要转换为整数的字符串。
返回值
该函数返回转换后的长整数,如果没有执行有效的转换,则返回零。
主要代码
void analysisIpAddr(char* addr,int* outip)
{
char* s=(char*)addr;
char* ss=NULL;
int n=0;
while (n<4&&(ss=strchr(s,'.'))!=NULL)
{
*ss=0;
outip[n++]=atoi(s);
s=ss+1;
}
if (n<4&&*s)
outip[n]=atoi(s);
}