21xrx.com
2025-03-27 07:00:23 Thursday
文章检索 我的文章 写文章
C++如何获取IP地址
2023-07-04 20:02:05 深夜i     20     0
C++ IP地址 获取

C++是一种广泛使用的编程语言,用于开发各种应用和系统。获取IP地址是在网络编程中一个非常重要的任务,特别是在创建客户端和服务端应用时。本文将介绍C++如何获取IP地址。

在C++中,获取IP地址需要使用系统库函数。下面是基于Windows操作系统的代码示例:

#include <iostream>
#include <string>
#include <winsock2.h>
#include <WS2tcpip.h>
#pragma comment(lib, "ws2_32.lib") //连接ws2_32.lib库文件
using namespace std;
int main()
{
  WSADATA wsaData;
  int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if (result != 0)
    cout << "WSAStartup failed: " << result << endl;
    return 1;
  
  char hostname[256];
  gethostname(hostname, sizeof(hostname));
  cout << "Hostname: " << hostname << endl;
  struct hostent* host;
  host = gethostbyname(hostname);
  if (host == NULL) {
    cout << "gethostbyname failed: " << WSAGetLastError() << endl;
    WSACleanup();
    return 1;
  }
  for (int i = 0; host->h_addr_list[i] != NULL; i++) {
    struct in_addr addr;
    memcpy(&addr, host->h_addr_list[i], sizeof(struct in_addr));
    string ip = inet_ntoa(addr);
    cout << "IP address: " << ip << endl;
  }
  WSACleanup();
  return 0;
}

这段代码使用了Windows Socket库,调用了`gethostname`和`gethostbyname`函数获取主机名和主机信息。`gethostbyname`返回一个指向`hostent`结构体的指针,其中包含了与主机名对应的IP地址信息。使用`inet_ntoa`函数将`in_addr`结构体类型的IP地址转换为字符串类型,即可获取主机的IP地址。

如果要获取其他主机的IP地址,需要将通过`gethostbyname`函数将主机名转换为IP地址。下面是基于Linux操作系统的代码示例:

#include <iostream>
#include <string>
#include <netdb.h>
#include <arpa/inet.h>
using namespace std;
int main(int argc, char* argv[])
{
  if (argc < 2) {
    cout << "Usage: " << argv[0] << " hostname" << endl;
    return 1;
  }
  struct hostent* host;
  host = gethostbyname(argv[1]);
  if (host == NULL)
    cout << "gethostbyname failed" << endl;
    return 1;
  
  for (int i = 0; host->h_addr_list[i] != NULL; i++) {
    struct in_addr addr;
    memcpy(&addr, host->h_addr_list[i], sizeof(struct in_addr));
    string ip = inet_ntoa(addr);
    cout << "IP address: " << ip << endl;
  }
  return 0;
}

在Linux系统中,同样调用`gethostbyname`函数获取主机名对应的IP地址信息,然后使用`inet_ntoa`将`in_addr`类型转换为字符串类型获取IP地址。

总之,无论是在Windows还是Linux系统中,获取IP地址都需要使用系统库函数。通过调用`gethostbyname`将主机名转换为IP地址,使用`inet_ntoa`将`in_addr`类型的IP地址转换为字符串类型,即可获取IP地址。

  
  

评论区