How can I use C ++ to obtain the IP address of a machine?

Source: Internet
Author: User

 

The method provided in this article is a complete solution with detailed implementation details. In fact, if you are familiar with the Windows Sockets API and learn some underlying Winsock knowledge. It is not difficult to obtain the IP address of a machine. A machine can have multiple NICs, so it may have multiple IP addresses. Currently, many enthusiasts have multiple NICs on their PCs. One network adapter is connected to the MODEM or ADSL adapter, and the other is connected to the LAN at home. For families with broadband connection conditions, this is a typical configuration. Everything becomes so simple once you know the solution. The following is a simple console program (the program name is getip1) provided in this Article. Its function is to display the IP address of the local machine. 1:


Figure 1 running figure of getip1

The following is the code of the getip1 program, which is simple:

//////////////////////////////////////// ////////////////////////
  
// Getip1.cpp
  
//
  
// This program reports the IP addresses of each Nic on the local machine
  
// The command for compiling through the command line is:
  
//
  
// Cl getip1.cpp wsock32.lib
  
//
  
// You must specify the path of the LIB library in the environment variable. You can run vcvars32.bat.
  
//
  
# Include <winsock. h>
  
# Include <wsipx. h>
  
# Include <wsnwlink. h>
  
# Include <stdio. h>
  
 
  
Int main ()
  
{
  
////////////////
  
// Initialize the Windows sockets API. The required version is version 1.1.
  
//
  
WORD wVersionRequested = MAKEWORD (1, 1 );
  
WSADATA wsaData;
  
If (WSAStartup (wVersionRequested, & wsaData )){
  
Printf ("WSAStartup failed % s", WSAGetLastError ());
  
Return-1;
  
}
  
 
  
//////////////////
  
// Obtain the host name.
  
//
  
Char hostname [256];
  
Int res = gethostname (hostname, sizeof (hostname ));
  
If (res! = 0 ){
  

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.