侧边栏壁纸
博主头像
银河驿站博主等级

行动起来,活在当下

  • 累计撰写 85 篇文章
  • 累计创建 17 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

C语言获取本机ip地址

Administrator
2023-07-15 / 0 评论 / 0 点赞 / 440 阅读 / 2333 字

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

评论区