IP地址字符串转换成16进制例程
写程序的时候经常遇到一个输入IP地址的情况,例如输入192.168.1.123,需要转换成对应的十六进制c0 a8 01 7b,所以就自己写了一个小demo,原理也很简单,就是检测输入的字符串中的"."的位置,然后分别提取出来进行转换,下面给出一个历程:
/*
author : ez
date : 2015/7/11
describe : Convert IP string into IP numeric
*/
#include <stdlib.h>
#include <string.h>
void ip_switch_func (const char *_str,unsigned char *_addr) {
const char ip_buf[20];
memcpy(ip_buf,_str,strlen(_str));
char *p1 = ip_buf;
char *p2 = ip_buf;
unsigned char* addr = (unsigned char*) _addr;
int i = 0;
while(*p1++ != '.');
*addr = atoi(p2);
p2 = p1;*(p1-1) = 0;
*(addr+1) = atoi(p2);
while(*p1++ != '.');
p2 = p1;*(p1-1) = 0;
*(addr+2) = atoi(p2);
while(*p1++ != '.');
p2 = p1;*(p1-1) = 0;
*(addr+3) = atoi(p2);
}
int main(){
const char _str[20]="192.168.1.123";
unsigned char _addr[4];
int i;
ip_switch_func(_str,_addr);
for(i=0;i<4;i++){
printf("%02x ",_addr[i]);
}
return 0;
}
运行效果:
例子中并没有检测ip地址的合理性,当然检测起来也不难,可以参考下面的网址
https://blog.****.net/life_binary/article/details/81366010