Converting long IP to dotted IP? (solved)

Mar 31, 2009 at 6:30am
Hi Guys,

In the code below, how do I convert long IP to dotted notation ?

1
2
3
4
5
6
7
8
char arr[] = "192.168.1.102";


unsigned char a, b, c, d;
sscanf(arr, "%hhu.%hhu.%hhu.%hhu", &a, &b, &c, &d );
unsigned long ipAddr = ( a << 24 ) | ( b << 16 ) | ( c << 8 ) | d;

Last edited on Mar 31, 2009 at 5:05pm
Mar 31, 2009 at 7:56am
1
2
3
char ip[] = "192.168.1.102";
long long_address = inet_addr (ip) ;
char *dot_ip = inet_ntoa(long_address);
Mar 31, 2009 at 8:55am
long long_address = inet_addr (ip) ;

Thanks for the reply dude, but correct me if I am wrong. Doesn't above statement returns address as inet_addr_t? I don't know how this will return long value?

Mar 31, 2009 at 9:33am
line 2 will return you the value in long from dotted value.
third line will return a dotted ip from long value. so you have both the functions.

i am not sure about
inet_addr_t
function actually. i use inet_add only.. have you tried it, isnt it working??
Mar 31, 2009 at 9:34am
might be it is for wide string, that is for wchar_t. its just an idea only.
Mar 31, 2009 at 3:05pm
No it does not work.
Mar 31, 2009 at 4:10pm
This printed the string back to me. Note: I changed your unsigned chars to unsigned shorts, else it gives me the error "stack around a was corrupted", though it seems to still work correctly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <cstdio>
int main() {
	char arr[] = "192.168.1.102\0 "; //extended to be able to fit up to maximum length
	unsigned short a, b, c, d;
	sscanf(arr, "%hu.%hu.%hu.%hu", &a, &b, &c, &d );
	arr[0] = '\0'; // cleared to make sure it's not just the same string coming back
	unsigned long ipAddr = ( a << 24 ) | ( b << 16 ) | ( c << 8 ) | d;
	a = (ipAddr & (0xff << 24)) >> 24;
	b = (ipAddr & (0xff << 16)) >> 16;
	c = (ipAddr & (0xff << 8)) >> 8;
	d = ipAddr & 0xff;
	sprintf(arr, "%hu.%hu.%hu.%hu", a, b, c, d);
	puts(arr);
}
Mar 31, 2009 at 4:19pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
        char ip[] = "192.168.1.102";
        long long_address = inet_addr (ip) ;
        struct in_addr addr;
        addr.s_addr = long_address;
        char *dot_ip = inet_ntoa(addr);

        printf("%s",dot_ip);
}


this will print 192.168.1.102 from its long value. i hope this is what you want.
Mar 31, 2009 at 4:50pm
Thanks a lot for the reply guys.

@writetonsharma: That's exactly what I needed. It is working perfect. Thanks again :)
Mar 31, 2009 at 5:23pm
cool.. :)
Topic archived. No new replies allowed.