Solved

gethostbyname function

Posted on 2006-10-28
2
208 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
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 how to create, access, and change arrays in the C programming language.

758 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

22 Experts available now in Live!

Get 1:1 Help Now