Skip to content

Instantly share code, notes, and snippets.

@jayjayswal
Created February 21, 2015 18:35
Show Gist options
  • Save jayjayswal/fc435fe261af9e45ccaf to your computer and use it in GitHub Desktop.
Save jayjayswal/fc435fe261af9e45ccaf to your computer and use it in GitHub Desktop.
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));
}
@Kiarashsedghi
Copy link

Thank you!!

@H-raf0
Copy link

H-raf0 commented Nov 15, 2022

very cool!
but you need to add #include <ctype.h> and i think that return (integer); instead of return (htonl(integer)); works well too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment