jay-jayswal
2/21/2015 - 6:35 PM

Convert IP address to integer and convert it back in c

Convert IP address to integer and convert it back in c

#include <stdio.h>
#include <stdlib.h>
union
{
    unsigned int integer;
    unsigned char byte[4];
} itoch;

main(){
	printf("Converting IP: 32.0.45.54\n");
	//--------- convert to int---------------------
	unsigned int a=stohi("32.0.45.54");
	printf("Integer value: %d\n",a);
	//--------- convert to char[]---------------------
	itoch.integer = a;
    	printf("char[] values: %u %u %u %u\n", itoch.byte[0], itoch.byte[1], itoch.byte[2], itoch.byte[3]);
}

int stohi(char *ip){
	char c;
	c = *ip;
	unsigned int integer;
	int val;
	int i,j=0;
	for (j=0;j<4;j++) {
		if (!isdigit(c)){  //first char is 0
			return (0);
		}
		val=0;
		for (i=0;i<3;i++) {
			if (isdigit(c)) {
				val = (val * 10) + (c - '0');
				c = *++ip;
			} else
				break;
		}
		if(val<0 || val>255){
			return (0);	
		}	
		if (c == '.') {
			integer=(integer<<8) | val;
			c = *++ip;
		} 
		else if(j==3 && c == '\0'){
			integer=(integer<<8) | val;
			break;
		}
			
	}
	if(c != '\0'){
		return (0);	
	}
	return (htonl(integer));
}