C + + Implementation to obtain domain name IP address _c language

Source: Internet
Author: User
Tags aliases

C + + implementation gets the IP address of the domain name

GetHostIP.cpp: Defines the entry point for a console application. #include "stdafx.h" #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> #include <w indows.h> #pragma comment (lib, "Ws2_32.lib") int main (int argc, char **argv) {//--------------------------------
  The---------//Declare and Initialize variables/* WSADATA structure is used to store the Windows AfxSocketInit initialization information that is returned by invoking the sockets global function. * This structure is used to store the Windows Sockets data returned after the WSAStartup function call.
  It contains the data that Winsock.dll executes.
  * * Wsadata wsadata;
 
  int Iresult; DWORD dwerror;
 
  /* Each word is 2 bytes in length, DWORD double word is 4 bytes, each byte is 8 bits/int i = 0;     struct Hostent *remotehost;          /* Domain name */char *host_name;        /* Host name */struct IN_ADDR addr;
 
  /*ip*/Char **palias;
    Validate the parameters if (argc!= 2) {printf ("Usage:gethostip hostname\n");
  return 1; The following procedures should be added here//1. When initializing WinSocket Iresult = WSAStartup (Makeword (2,2), &wsadata);/* & Address *//2.
  Check that the socket is initialized successfully, that is, whether the socket is equal to 0, and if initialization is unsuccessful, you should give an error alert and end the program. if (iresult!=0) {printf ("Initialization failed!\n");
  return 1;
  /////////////////end///////////////////////////////////host_name = argv[1];
  printf ("Calling gethostbyname with%s\n", host_name); The following procedures should be added here//1.
  Use the function gethostbyname () to get a pointer to the given host name.
  RemoteHost = gethostbyname (HOST_NAME); 2. You should familiarize yourself with the structure of the structure pointer//The function is stated as follows: struct hostent* gethostbyname (const char *name)//The program to be added here is as follows//1. If the host structure pointer returned by the above function is null (NULL), the following processing is done://A. Use function int wsagetlasterror (void) to check for current network errors,//b. The type of error that is returned and processed accordingly, for example, if
    No host error was found (this function returns Wsahost_not_found) if (remotehost = = NULL) {//printf ("gethostbynameerror:%d", WSAGetLastError ());
  return 1;
    }else{//2. If the returned host pointer is not empty, do the following://A. Print out the following parameters: Host name and IP address, if the host corresponds to multiple IP addresses, should be listed separately.
    printf ("Host name:%s\n", remotehost->h_name); for (i=0;; i++) {if (remotehost->h_addr_list[i]!=0) {*/* copies p from the cache into the addr * while addr. S_un. 
      SADDR * in_addr ipaddr; * Ipaddr.s_un. 
      S_ADDR = inet_addr ("127.0.0.1");* is to convert the IP address in the form of a string into a 0xXXXXXXXX address format. 
        * * addr.s_addr = * (u_long*) remotehost->h_addr_list[i]; printf ("IP #%d:%s\n", I,inet_ntoa (addr)); /* The Inet_ntoa () function converts the network address into a binary digital correlation function: Inet_aton, INET_NTOA/* for (i=0;;
      i++) {Char *p = remotehost->h_addr_list[i];
      if (p==null) break; /* Copy p from cache into addr * and addr. S_un. 
      SADDR * in_addr ipaddr; * Ipaddr.s_un. 
      S_ADDR = inet_addr ("127.0.0.1");
      * is to convert the IP address in the form of a string into a 0xXXXXXXXX address format. * memcpy (&addr. S_un. 
      S_addr,p,remotehost->h_length);
     
    printf ("IP address:%s\n", Inet_ntoa (addr)); * *////here should be added to the program below//after the completion of the program should be properly tested, need to be tested as follows://1. Test host structure pointer fetch failed//2. Test hosts//3 that contain multiple IP addresses. You can think of any anomalies that may arise/////////////////end///////////////////////////////////System ("pause");
/* Prevent form close function/return 0;
 }

Here's a detailed description of the core gethostbyname of the code below.

To use this thing, you first need to include 2 header files:

#include <netdb.h>
#include <sys/socket.h>
struct hostent *gethostbyname (const char *name);

The incoming value of this function is the domain name or host name, such as "www.google.com", "WPC", and so on.
The outgoing value, which is a hostent structure (as follows). If the function call fails, NULL is returned.

struct Hostent {
   char *h_name;
   char **h_aliases;
   int h_addrtype;
   int h_length;
   char **h_addr_list;
};

Explain this structure, where:

The

Char *h_name represents the canonical name of the host. For example, Www.google.com's canonical name is actually www.l.google.com. The
Char **h_aliases represents the alias of the host. Www.google.com is Google's own alias. Sometimes, some hosts may have several aliases, these, in fact, are in order to easily user memory for their own site to take more names.
int H_addrtype represents the type of host IP address, whether it is IPv4 (af_inet), or IPv6 (AF_INET6)
int h_length Represents the length of the host IP address
int **h_addr_lisst represents the IP address of the host, note that this is stored in network byte order. Do not directly with printf with the%s parameter to hit this thing, there will be a problem wow. So to really need to print out this IP, you need to call Inet_ntop ().
Const char *inet_ntop (int af, const void *SRC, char *dst, socklen_t cnt):
This function is to convert the network address structure of type AF to a string form of host sequence, storing In a string of CNT length. The
function, in fact, is to return a pointer to DST. If the function calls an error, the return value is null.
The following is a routine with detailed comments.

#include <netdb.h>
#include <sys/socket.h>
int main (int argc, char **argv)
{
char *ptr,** Pptr;
struct hostent *hptr;
Char str[32];
/* Get the first parameter after the command, that is to resolve the domain name or host name * * *
ptr = argv[1];
/* Call gethostbyname (). Call results exist in HPTR/
if ((hptr = gethostbyname (PTR) = NULL)
{
printf ("GetHostByName error for host:%s/n", PT R);
return 0; /* If the call gethostbyname error, return 1 * * * * *
will host the specification name to play out
/printf ("Official hostname:%s/n", hptr->h_name);
/* The host may have multiple aliases, and all aliases will be typed individually for
(pptr = hptr->h_aliases; *pptr!= NULL; pptr++)
printf ("alias:%s/n", *pptr);
/* Base address type, call out/
switch (hptr->h_addrtype) {case
af_inet: Case
Af_inet6:
pptr =hptr->h_addr_list;
* * All the addresses you just got are typed out. where the Inet_ntop () function is invoked */for
(; *pptr!=null;pptr++)
printf ("address:%s/n", Inet_ntop (Hptr->h_addrtype, * Pptr, str, sizeof (str));
break;
Default:
printf ("Unknown address type/n");
break;
return 0;

Additional code to obtain public network and intranet IP:

BOOL Getpublicip (string& IP)
{
  int  sock;
  char **pptr = NULL;
  struct sockaddr_in  destaddr;
  struct hostent  *ptr = NULL;
  Char destip[128];

  Sock = socket (af_inet,sock_stream,0);
  if (-1 = sock) {
    perror ("creat socket Failed");
    return false;
  }
  Bzero ((void *) &destaddr,sizeof (DESTADDR));
  destaddr.sin_family = af_inet;
  Destaddr.sin_port = Htons ();
  ptr = gethostbyname ("www.ip138.com");
  if (NULL = = ptr) {
    perror ("gethostbyname error");
    return false;
  }
  for (pptr=ptr->h_addr_list; NULL!= *pptr; ++PPTR) {
    inet_ntop (ptr->h_addrtype,*pptr,destip,sizeof (Destip));
    printf ("addr:%s\n", Destip);
    ip = destip;
    return true;
  }
  return true;
}

Get intranet IP

int Getlocalip (char* outip)
{
#ifndef WIN32
	int i=0;
	int sockfd;
	struct ifconf ifconf;
	Char buf[512];
	struct Ifreq *ifreq;
	char* IP;
	Initialization of ifconf
	Ifconf.ifc_len = the;
	Ifconf.ifc_buf = buf;
	strcpy (Outip, "127.0.0.1");
	if ((SOCKFD = socket (af_inet, SOCK_DGRAM, 0)) <0)
	{
		return-1;
	}
	IOCTL (SOCKFD, siocgifconf, &ifconf);  Get all interface information close
	(SOCKFD);
	The next one gets the IP address
	ifreq = (struct ifreq*) buf;
	For (i= (ifconf.ifc_len/sizeof (struct ifreq)); i>0; i--)
	{
		IP = inet_ntoa ((struct sockaddr_in*) & ( IFREQ->IFR_ADDR))->sin_addr);


		if (strcmp (IP, "127.0.0.1") ==0)//exclude 127.0.0.1, continue to the next
		{
			ifreq++;
			Continue
		}
	}
	strcpy (OUTIP,IP);
	return 0;
#else return
	0;
#endif
	
}

Related Article

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: info-contact@alibabacloud.com 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.