侧边栏壁纸
  • 累计撰写 82 篇文章
  • 累计创建 16 个标签
  • 累计收到 1 条评论

C语言获取本机ip地址

秋山人家
2023-07-15 / 0 评论 / 0 点赞 / 247 阅读 / 310 字
温馨提示:
本文最后更新于 2023-07-15,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

linux平台获取ip地址

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int main() {
    char hostname[256];
    char ip[INET6_ADDRSTRLEN];

    /**  获取主机名 **/
    if (gethostname(hostname, sizeof(hostname)) == -1) {
        perror("Failed to get hostname");
        return -1;
    }
    
    struct hostent *he;
    struct in_addr **addr_list;
    
    /**  获取主机信息 **/
    if ((he = gethostbyname(hostname)) == NULL) {
        herror("Failed to get host by name");
        return -1;
    }
    
    addr_list = (struct in_addr **)he->h_addr_list;
    
    /**  获取IP地址 **/
    for (int i = 0; addr_list[i] != NULL; i++) {
        strcpy(ip, inet_ntoa(*addr_list[i]));
        printf("IP address: %s\n", ip);
    }

    return 0;
}

windows平台获取ip地址

#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>

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

int main() {
    WSADATA wsaData;

    // 初始化Winsock库
    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
        fprintf(stderr, "Failed to initialize Winsock\n");
        return -1;
    }
    
    char hostname[256];
    char ip[INET6_ADDRSTRLEN];
    
    /**  获取主机名 **/
    if (gethostname(hostname, sizeof(hostname)) == -1) {
        fprintf(stderr, "Failed to get hostname\n");
        WSACleanup();
        return -1;
    }
    
    struct hostent *he;
    struct in_addr **addr_list;
    
    /**  获取主机信息 **/
    if ((he = gethostbyname(hostname)) == NULL) {
        fprintf(stderr, "Failed to get host by name\n");
        WSACleanup();
        return -1;
    }
    
    addr_list = (struct in_addr **)he->h_addr_list;
    
    /**  获取IP地址 **/
    for (int i = 0; addr_list[i] != NULL; i++) {
        strcpy(ip, inet_ntoa(*addr_list[i]));
        printf("IP address: %s\n", ip);
    }
    
    WSACleanup();

    return 0;
}
0

评论区