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 ){