c++

c++如何获取本机ip

小亿
132
2024-08-01 19:39:11
栏目: 编程语言

要在C++中获取本机IP地址,可以使用如下方法:

#include <iostream>
#include <string>
#include <winsock2.h>
#include <ws2tcpip.h>

#pragma comment(lib, "ws2_32.lib")

int main() {
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        std::cerr << "WSAStartup failed" << std::endl;
        return 1;
    }

    char hostname[256];
    if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) {
        std::cerr << "Error getting hostname" << std::endl;
        WSACleanup();
        return 1;
    }

    struct addrinfo* result = NULL;
    struct addrinfo hints;

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    if (getaddrinfo(hostname, NULL, &hints, &result) != 0) {
        std::cerr << "Error getting address info" << std::endl;
        WSACleanup();
        return 1;
    }

    struct sockaddr_in* addr = (struct sockaddr_in*) result->ai_addr;
    char ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &addr->sin_addr, ip, sizeof(ip));

    std::cout << "Hostname: " << hostname << std::endl;
    std::cout << "IP Address: " << ip << std::endl;

    freeaddrinfo(result);
    WSACleanup();

    return 0;
}

这段代码首先初始化Winsock库,然后使用gethostname函数获取本地主机名,接着使用getaddrinfo函数获取主机地址信息,最后通过inet_ntop函数将sockaddr_in结构体中的IP地址转换为字符串格式并输出。

0
看了该问题的人还看了