How to use C + + programming to obtain the IP address of a machine? __linux

Source: Internet
Author: User
Tags knowledge base
The essence of the VC knowledge Base and the previous online magazines are described in detail in this age-old problem. The approach provided in this article is a more complete solution with detailed implementation details. I hope you have a thorough understanding of this issue. In fact, if you are familiar with Windows sockets API, and understand some of the underlying Winsock knowledge. So it's not difficult to get the IP address of a machine. A machine can have more than one NIC, so it may have multiple IP addresses. At present many enthusiasts are equipped with many PC network card. One of the network cards is connected to the modem or the ADSL adapter, and the other is connected to the home local area network (LAN). For families with broadband connectivity, this is a typical configuration. Anything, once you know the solution, everything will be so simple. The following is a simple console program (program named GETIP1) provided in this article that displays the IP address of this computer. As shown in Figure one:


Figure one getip1 the running picture

Here is the code for the GETIP1 program, very simple:
Getip1.cpp///This program reports that the IP address//Command line compilation command for each network card on this machine is:/ ///CL Getip1.cpp wsock32.lib////Please make sure that the Lib library path is correctly specified in the environment variable; you can run Vcvars32.bat//#include <winsock.h> #include <wsi px.h> #include <wsnwlink.h> #include <stdio.h> int main () {//////////////////initialization of Windows sockets Api.
   Required version 1.1//WORD wversionrequested = Makeword (1, 1);
   Wsadata Wsadata;
      if (WSAStartup (wversionrequested, &wsadata)) {printf ("WSAStartup failed%s/n", WSAGetLastError ());
   return-1;
   ////////////////////Get host name.
   Char hostname[256];
   int res = GETHOSTNAME (hostname, sizeof (hostname));
      if (res!= 0) {printf ("Error:%u/n", WSAGetLastError ());
   return-1;
   printf ("hostname=%s/n", hostname); 
   Gets the host information based on the host name.
   hostent* phostent = gethostbyname (hostname); if (phostent==null) {printf ("Error:%u/n", WSAGetLastError ());
   return-1;
   ////////////////////Resolves the returned hostent information.
   hostent& he = *phostent;
   
   printf ("name=%s/naliases=%s/naddrtype=%d/nlength=%d/n", He.h_name, He.h_aliases, He.h_addrtype, he.h_length);
   Sockaddr_in sa; for (int nadapter=0; he.h_addr_list[nadapter]; nadapter++) {memcpy (&sa.sin_addr.s_addr, he.h_addr_list[nadapt
      Er],he.h_length);
      The IP address of the output machine. printf ("Address:%s/n", Inet_ntoa (SA.SIN_ADDR));
   Display address string}////////////////////Terminate Windows sockets API//WSACleanup ();
return 0;      }
To use Winsock, you must first call WSAStartup and don't forget to call WSACleanup at the end. To obtain an IP address, you must first obtain the machine's hostname (host name), call GetHostName can be implemented, with the hostname, and then call gethostbyname to obtain more host information including the IP address. gethostbyname returns a pointer to the Hostent data structure, which is defined in the <winsock.h> file:
From winsock.h
struct  hostent {
  char    FAR * H_NAME;            /* Official host name *    /char FAR * FAR * h_aliases;   /* Name list * * Short   h_addrtype;              /* Host Address Type * * Short   h_length;                /* Address length    /char FAR * FAR * h_addr_list/* Address list * *
;
This is a typical data structure used by the underlying APIs, and many people are not familiar with it. In fact, hostent is a variable length data structure, h_name is the hostname, the value in the example program is "Zxn.hangwire.sdb". No alias (h_aliases). H_addrtype is the address type (or also called the address family), in the example program the value is 2 (af_inet = Internet, other content see WINSOCK.H). H_length is the length of each address, in bytes. Because the length of the IP address is 4 bytes, the value in the example program is 4,h_addr_list is the starting point of the address array, which is stored one after the other, and ends with a null. Each X.Y.Z.W number occupies one byte. In order to format an IP address as a X.Y.Z.W, an array of addresses must be copied first to a data structure called SOCKADDR, and then a special function Inet_ntoa called. Figure Two is the hostent structure in memory storage diagram:


Diagram II hostent structure in memory storage diagram

Believe that the above explanation is supplemented with the reading code, you will no longer be unfamiliar with the hostent structure.

Right now. NET rage, with C # language programming also become a fashion, if anyone want to know how to use C # to solve this problem, please refer to the essence of the relevant content:
"C # programming how to get the IP address of a machine. ”


Finally, I wish to have a happy programming.

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.