Wednesday 18 May 2011

Code for finding Ip address of server

#include <stdio.h> /*using for printf*/
#include <netdb.h> /*used for gethostbyname() function*/
#include <sys/types.h>

int main(int argc, char *argv[])
{
  struct hostent *he;/*making a structure to hold all the info related to host like hostname and host ip*/
  if (argc!=2)/*if no arguments are passed*/
  {
  argv[1]="www.google.com";/*then make www.google.com as our default option*/
  }
  he=gethostbyname(argv[1]);/*fills the he structure instance with hostname and ip address*/
  if (he==NULL)/*if he is NULL that means the host is not found*/
  {
  printf("gethostbyname() error\n");
  exit(-1);/*exit the program with error*/
  }
  printf("Hostname : %s\n",he->h_name); /* prints the hostname */
  /*inet_ntoa converts string IP addresses to long*/
  printf("IP Address: %s\n",inet_ntoa(*((struct in_addr *)he->h_addr))); /* prints IP address */
}




No comments:

Post a Comment