c++如何獲取本機(jī)ip

c++
小億
129
2024-08-01 19:39:11
欄目: 編程語言

要在C++中獲取本機(jī)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庫(kù),然后使用gethostname函數(shù)獲取本地主機(jī)名,接著使用getaddrinfo函數(shù)獲取主機(jī)地址信息,最后通過inet_ntop函數(shù)將sockaddr_in結(jié)構(gòu)體中的IP地址轉(zhuǎn)換為字符串格式并輸出。

0