C++ how do I get the local IP address

  • 2020-06-01 10:35:45
  • OfStack

This article for you to share C++ get the local ip address program, for your reference, the specific content is as follows

The header file


#include <WinSock2.h>
#pragma comment(lib,"ws2_32")// Link to the ws2_32 Dynamic link library 

class CInitSock
{
public:
  CInitSock(BYTE minorVer = 2,BYTE majorVer = 2)
  {
    WSADATA wsaData;
    WORD VersionRequset;
    VersionRequset = MAKEWORD(minorVer,majorVer);
    // loading winsock library 
    if (WSAStartup(VersionRequset,&wsaData)!=0)
    {
      // loading winsock Library failed, launch 
      exit(0);
    }
  }
  ~CInitSock()
  {
    WSACleanup();
  }
};

Source file


#include <iostream>
#include "a.h"
using namespace std;
CInitSock Initsock;
bool GetIp();
int main()
{
  GetIp();
  return 0;
}
bool GetIp()
{
  char szText[256];
  // Gets the local host name 
  int iRet;
  iRet = gethostname(szText,256);
  int a = WSAGetLastError();
  if (iRet!=0)
  {
    printf("gethostname() Failed!");
    return FALSE;
  }
  // Get the address information by the host name 
  HOSTENT *host = gethostbyname(szText);
  if (NULL==host)
  {
    printf("gethostbyname() Failed!");
    return false;
  }
  in_addr PcAddr;
  for (int i=0;;i++)
  {
    char *p = host->h_addr_list[i];
    if (NULL==p)
    {
      break;
    }
    memcpy(&(PcAddr.S_un.S_addr),p,host->h_length);
    char*szIP = ::inet_ntoa(PcAddr);
    printf(" This machine is the ip The address is: %s\n",szIP);
  }

  system("pause");
}

Related articles: