A
awasthi.ashish
Hi friends,
I am writing a simple program to convert an IP address from a
hexadecimal form to dotted-notation form. However, for some reason I am
having problem getting it to work.Here it is:
/* print an ip address, given a hexadecimal number in host byte order
*/
char *get_ip (unsigned int *number)
{
u_int8_t ip1, ip2, ip3, ip4, ip5, ip6;
char *address;
ip1 = (u_int8_t) (*number );
ip2 = (u_int8_t) (*( number + 1 ));
ip3 = (u_int8_t) (*( number + 2 ));
ip4 = (u_int8_t) (*( number + 3 ));
/*change the order of ip1, ip2, etc. because the host is a
little-endian machine */
asprintf(&address, "%u . %u . %u . %u", ip4, ip3, ip2, ip1);
return address;
}
int main()
{
unsigned int temp =0xD8736CF5; /* equivalent to 3631443187 or
216.115.108.245 */
printf("\n %s \n", get_ip(&temp));
return 0;
}
Somehow, when I run this code, I always get the last quartet right
(i.e. 245, which is also the first byte in a little endian machine);
but the remaining bytes are incorrect, and vary on different runs. A
few results I have gotten are: 1.154.168.245, 1.194.188.245,
1.244.198.245.
I tried it for different IP addresses. Always I get the last byte ( of
IP address) right, but the remaining are incorrect.
I suppose I am missing something very simple, but I cannot find it. Can
anybody help please?
Thanks!
I am writing a simple program to convert an IP address from a
hexadecimal form to dotted-notation form. However, for some reason I am
having problem getting it to work.Here it is:
/* print an ip address, given a hexadecimal number in host byte order
*/
char *get_ip (unsigned int *number)
{
u_int8_t ip1, ip2, ip3, ip4, ip5, ip6;
char *address;
ip1 = (u_int8_t) (*number );
ip2 = (u_int8_t) (*( number + 1 ));
ip3 = (u_int8_t) (*( number + 2 ));
ip4 = (u_int8_t) (*( number + 3 ));
/*change the order of ip1, ip2, etc. because the host is a
little-endian machine */
asprintf(&address, "%u . %u . %u . %u", ip4, ip3, ip2, ip1);
return address;
}
int main()
{
unsigned int temp =0xD8736CF5; /* equivalent to 3631443187 or
216.115.108.245 */
printf("\n %s \n", get_ip(&temp));
return 0;
}
Somehow, when I run this code, I always get the last quartet right
(i.e. 245, which is also the first byte in a little endian machine);
but the remaining bytes are incorrect, and vary on different runs. A
few results I have gotten are: 1.154.168.245, 1.194.188.245,
1.244.198.245.
I tried it for different IP addresses. Always I get the last byte ( of
IP address) right, but the remaining are incorrect.
I suppose I am missing something very simple, but I cannot find it. Can
anybody help please?
Thanks!