• C语言获取本机ip


    一、参考网址

      1、c语言获取本机IP

    二、源码

     1 #include <stdio.h>
     2 #include <stdint.h>
     3 #include <stdlib.h>
     4 #include <stdarg.h>
     5 #include <time.h>
     6 #include <sys/time.h>
     7 #include <pthread.h>
     8 #include <netinet/in.h>
     9 #include <arpa/inet.h>
    10 #include <sys/socket.h>
    11 #include <netdb.h>
    12 #include <signal.h>
    13 #include <sys/types.h>
    14 #include <unistd.h>
    15 #include <ctype.h>
    16 #include <ifaddrs.h>
    17 #include <string.h>
    18 #include <assert.h>
    19 #include <poll.h>
    20 #include <errno.h>
    21  
    22 static char *getip()
    23 {
    24     struct ifaddrs *ifaddr, *ifa;
    25     int family, s;
    26     char *host = NULL;
    27  
    28     if (getifaddrs(&ifaddr) == -1) {
    29         perror("getifaddrs");
    30         return NULL;
    31     }
    32  
    33     for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
    34         if (ifa->ifa_addr == NULL)
    35             continue;
    36  
    37         family = ifa->ifa_addr->sa_family;
    38  
    39         if (!strcmp(ifa->ifa_name, "lo"))
    40             continue;
    41         if (family == AF_INET) {
    42             if ((host = malloc(NI_MAXHOST)) == NULL)
    43                 return NULL;
    44             s = getnameinfo(ifa->ifa_addr,
    45                     (family == AF_INET) ? sizeof(struct sockaddr_in) :
    46                     sizeof(struct sockaddr_in6),
    47                     host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
    48             if (s != 0) {
    49                 return NULL;
    50             }
    51             freeifaddrs(ifaddr);
    52             return host;
    53         }
    54     }
    55     return NULL;
    56 }
  • 相关阅读:
    k8s前期部署准备
    树莓派安装Gitlab-runner
    GitLab CI/CD 报错
    测试
    LVS结合keepalive
    LVS实现负载均衡安装配置详解
    LVS实现负载均衡原理
    私有仓库 gitlab 部署笔记
    Docker 案例: 在容器中部署静态网站
    docker 容器的启动方式
  • 原文地址:https://www.cnblogs.com/shanyu20/p/11929223.html
Copyright © 2020-2023  润新知