ubuntu-C++拿到本机IP地址

前端之家收集整理的这篇文章主要介绍了ubuntu-C++拿到本机IP地址前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

环境

ubuntu 14.04

场景

自动驾驶算法架构中,存在多台机器,通过各台主机的IP确认机器功能,实现多台机器共用同一套代码,实现系统一键启动功能

方法

#include <stdio.h> 
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h> 
#include <string.h> 
#include <arpa/inet.h>



#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <string>


int main (int argc,const char * argv[]) {

    struct ifaddrs * ifAddrStruct=NULL;
    struct ifaddrs * ifa=NULL;
    void * tmpAddrPtr=NULL;

    getifaddrs(&ifAddrStruct);

    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
        if (!ifa->ifa_addr) {
            continue;
        }
        if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4
            // is a valid IP4 Address
            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET,tmpAddrPtr,addressBuffer,INET_ADDRSTRLEN);
            printf("%s IP Address %s\n",ifa->ifa_name,addressBuffer); 
        } else if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6
            // is a valid IP6 Address
            tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
            char addressBuffer[INET6_ADDRSTRLEN];
            inet_ntop(AF_INET6,INET6_ADDRSTRLEN);
            printf("%s IP Address %s\n",addressBuffer); 
        } 
    }
    if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
    return 0;
}
原文链接:https://www.f2er.com/ubuntu/353105.html

猜你在找的Ubuntu相关文章