views:

50

answers:

4

I am having a pointer *ip_address_server which holds the ip address of the server :

   in_addr * address = (in_addr * )record->h_addr;
    char *ip_address_server = inet_ntoa(* address);

Clearly, when I use printf to print the value of it, it gets nicely printed.

printf("p address %s" , ip_address_server);

But now if I declare an array of say size 20 to hold the value then I need to copy the content from the pointer to the array.

char host_name[20];

To copy the value I used a for loop. But the value that I print later is not the right value.

for(int i = 0; ip_address_server[i] != '\0'; i++) 
        host_name[i] = ip_address_server[i];
    printf("hostname %s \n" , host_name);

I think there is some error with the terminating condition.

Am I wrong in my approach or is there any alternative way out for this?

+1  A: 
  1. use memcpy() function instead of copying values byte by byte
  2. you need to copy the terminating NULL character, otherwise you get junk. This applies to both memcpy call and your loop
  3. Host name can be larger than 20 bytes. I don't remember exact value at the moment, but I'd allocate at least 100-byte array. Upd: Wikipedia says "Each label may contain up to 63 characters. The full domain name may not exceed a total length of 253 characters.[9] In practice, some domain registries may have shorter limits."
Eugene Mayevski 'EldoS Corp
`inet_ntoa` will only convert an IPv4 address from the 'in_addr' form to the `dots-and-number` string form, it doesn't do any reverse DNS lookups or such, so it needs only 16 chars.
Eugen Constantin Dinca
You're right, I've overlooked this.
Eugene Mayevski 'EldoS Corp
+4  A: 

Your loop does not copy the '\0' byte.

Also, why don't you just use strcpy (or safer strncpy) or memcpy?

birryree
Thanks copying \0 made it worked.
abhishekgupta92
+1  A: 

You are missing the nul character at the end of the char array. Your for loop copies all the characters but not the nul character. To fix this you'll have to copy it yourself once outside the loop as:

int i;
for( i = 0; ip_address_server[i] != '\0'; i++) 
        host_name[i] = ip_address_server[i];
host_name[i] = 0; // add nul char.
printf("hostname %s \n" , host_name);
codaddict
Your example won't work since `i` is not defined outside the `for` statement.
Ferdinand Beyer
@Ferdinand: Thanks for pointing.
codaddict
Yeah got it.. working. thanks
abhishekgupta92
+1  A: 

Safe & better way to do it:

snprintf(host_name, sizeof(host_name), "%s", ip_address_server);
kotlinski
thanks dis really worked like a charm
abhishekgupta92