程序如下:
#include <stdio.h> int net_aton(const char *cp, struct in_addr *inp); struct in_addr { unsigned int s_addr; }; int main( ) { struct in_addr addr0 ; const char *str="128.2.194.242" ; int d32 ; d32 = net_aton(str, &addr0) ; printf("IP ADDRESS is : 0x%x", d32); return 0 ; } int net_aton(const char *cp, struct in_addr *inp) { char n[3] = {0} ; char k, i=0,j=0 ; int y=0,temp ; while(cp[i]!='\0') { if( cp[i]=='.' ) { n[j] = i ; j++ ; } i++ ; } if( (n[0] - 0) >= 1) { temp=cp[0]-'0' ; for(i=0; i<n[0]-1; i++) temp=temp*10+cp[i+1]-'0' ; y= ( y | temp)<<8 ; } i=0 ; while( i<2 ) { if(n[i+1]-n[i]>1) { k=n[i]+1 ; temp=cp[k]-'0' ; for(;k<n[i+1]-1;k++) temp=temp*10+cp[k+1]-'0' ; y= ( y | temp)<<8 ; } i++; } if(n[i]<14) // 把其后的数字符变为10进制数 { k=n[i]+1; // k为第1个数字符的编号 temp=cp[k]-'0'; while( cp[k+1] != '\0' ) { temp=temp*10+cp[k+1]-'0'; k++; } y = y | temp; } inp->s_addr = y; return y; }运行结果:
IP ADDRESS is 0x8002c2f2