整数型的ipv4地址为无符号32位整数,注意这点即可
#include <stdio.h> #include <string.h> #include <stdlib.h> void str2int(char *str, unsigned int *ip) { int cnt = 0; char num_buf[5] = {0}; int buf_cnt = 0; unsigned int ip_value = 0; int bit = 3; while(1){ if(str[cnt] >= '0' && str[cnt] <= '9' && str[cnt] != '\0'){ num_buf[buf_cnt++] = str[cnt]; } else{ ip_value += strtol(num_buf,NULL,0)*(1<<(bit*8)); memset(num_buf,0,5); buf_cnt = 0; bit--; } if(str[cnt] == '\0'){ break; } else{ cnt++; } } *ip = ip_value; } void int2str(unsigned int ip, char *str) { char part[10] = {0}; for(int i = 0; i < 4;i++){ sprintf(part,"%d.",ip / (1<<((3-i)*8))); strcat(str,part); memset(part,0,10); ip = ip%(1<<((3-i)*8)); } str[strlen(str)-1] = '\0'; } int main(void) { unsigned int ip_addr; char buf[20] = {0}; char ip_str[20] = {0}; unsigned int tmp; // strcpy(ip_str,"10.0.3.193"); //ip_addr = 167969729; while((scanf("%s",ip_str)) != EOF){ scanf("%d",&ip_addr); str2int(ip_str, &tmp); printf("%u\n",tmp); int2str(ip_addr,buf); printf("%s\n",buf); memset(buf,0,20); memset(ip_str,0,20); } return 0; }