?
Solved

gethostbyname function

Posted on 2006-10-28
2
Medium Priority
?
254 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 53

Accepted Solution

by:
Infinity08 earned 2000 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
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…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
Suggested Courses

752 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