IP地址字符串转换成16进制例程

您所在的位置:网站首页 ip地址的十六进制 IP地址字符串转换成16进制例程

IP地址字符串转换成16进制例程

#IP地址字符串转换成16进制例程| 来源: 网络整理| 查看: 265

写程序的时候经常遇到一个输入IP地址的情况,例如输入192.168.1.123,需要转换成对应的十六进制c0 a8 01 7b,所以就自己写了一个小demo,原理也很简单,就是检测输入的字符串中的"."的位置,然后分别提取出来进行转换,下面给出一个历程:

/*   author : ez   date : 2015/7/11   describe : Convert IP string into IP numeric */   #include #include   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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3