Solved

gethostbyname function

Posted on 2006-10-28
2
221 Views
Last Modified: 2010-08-05
Here is my code, for some reason it will sometimes print portions of the IP as a negative number, I cant figure it out, I've tried casting to an unsigned int, i've tried bitwise & with 127, i've tried right shifts....

 char cHost[256];
 char ip[4];
 int i;
 WSADATA wsa;
 HOSTENT *ht;

 printf("Hostname: ");
 scanf("%s",cHost);

 if (!(WSAStartup(MAKEWORD(2, 2), &wsa) != 0))
 {
   ht = gethostbyname(cHost);
   if (!(ht == NULL))
   {
    for (i = 0; i < ht->h_length; ++i)
     ip[i] = (unsigned int)(ht->h_addr_list[0][i]);

     printf(" -> %s resolved to %d.%d.%d.%d\n", cHost,ip[0],ip[1],ip[2],ip[3]);
      }
      else
       printf("Unable to resolve %s\n",cHost);
  }
  else
   printf("\nERROR: Unable to start WSA.\n");
 
  WSACleanup();



Thanks.

Brian
0
Comment
Question by:BrianGEFF719
2 Comments
 
LVL 53

Accepted Solution

by:
Infinity08 earned 500 total points
ID: 17825036
Try :

    unsigned char ip[4];
0
 
LVL 8

Expert Comment

by:deepu chandran
ID: 17825132
hi,
>>  char ip[4];    change this as char *ip;

>> ip[i] = (unsigned int)(ht->h_addr_list[0][i]);    as ip[i] = (char *)(ht->h_addr_list[0][i]);

>>printf(" -> %s resolved to %d.%d.%d.%d\n", cHost,ip[0],ip[1],ip[2],ip[3]);
    printf(" -> %s resolved to %c.%c.%c.%c\n", cHost,*(ip+0),*(ip+1),*(ip+2),*(ip+3));
I think this will help you

Deepu
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now