Use C to convert domain name to IP (domain name resolution) under Linux

Source: Internet
Author: User
Tags function prototype get ip

Simply call a function to gethostbyname (),gethostbyname () returns a hostent structure pointer to the host name and address information that corresponds to the given host name. The declaration of the structure is consistent with the GETHOSTADDR (). Here is the function prototype:

under Windows platform

#include <winsock2.h>

struct hostent far *pascal far gethostbyname (const char

Far * name);

Name: A pointer to the host name.

under Linux platform

#include <netdb.h>

struct hostent *gethostbyname (const char * hostname);

Return: Non-null pointer--Success, NULL pointer--error, set H_errno

C Language Program implementation:

 #include <stdio.h> #include <stdlib.h> #include <errno.h> #include < netdb.h> #include <sys/types.h> #include <netinet/in  .h> int  Main (int  argc, char  *argv[]) { Span class= "KWRD" >struct  hostent *h; char  hostname[40]; printf ( "Please enter the domain name \ n" ); scanf ( "%s" , hostname); GetChar (); if  ((H=gethostbyname (hostname)) ==null)     {fprintf (stderr, "Cannot get IP\n" ); Exit (1); } printf ( "HostName:%s\n" , H->h_name); printf ( "IP Address:%s\n" , Inet_ntoa (* ((struct  in_addr *) h->h  (_ADDR))); return  exit_success;} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.