linux c++11 获取本机ip地址 ipv4

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

using namespace std;
int get_ip_linux(int ipv4_6, std::list<std::string>& out_list_ip){
    int ret_val = 0;
    struct ifaddrs * ifAddrStruct = NULL;
    void * tmpAddrPtr = NULL;
    ret_val = getifaddrs(&ifAddrStruct);
    if (0 != ret_val){
        ret_val = errno;
        return ret_val;
    }
    std::string str_ipvX;
    int padress_buf_len = 0;
    char addressBuffer[INET6_ADDRSTRLEN] = {0};
    if (AF_INET6 == ipv4_6)
            padress_buf_len = INET6_ADDRSTRLEN;
    else
        padress_buf_len = INET_ADDRSTRLEN;
    while (NULL != ifAddrStruct ){
        if (ipv4_6 == ifAddrStruct->ifa_addr->sa_family ){
            // is a valid IP4 Address
            tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
            inet_ntop(ipv4_6, tmpAddrPtr, addressBuffer, padress_buf_len);
            str_ipvX = std::string(addressBuffer);
            out_list_ip.push_back(str_ipvX);
            memset(addressBuffer, 0, padress_buf_len);
        } 
        ifAddrStruct=ifAddrStruct->ifa_next;
    }
    return ret_val;
}

int get_ipv4_linux(std::list<std::string>& out_list_ip4){
    return get_ip_linux(AF_INET, out_list_ip4);
}
int main(){
	std::list<std::string> ipv4;
	int ret_val = get_ipv4_linux(ipv4);
	if (0 != ret_val){
    	cout << "error, ipv4, id = " << ret_val << endl;
	}else{
    	int index = 0;
    	for (auto item: ipv4){
        	cout << "index = " << ++index;
        	cout << ", ipv4 = " << item.c_str() << endl;
    	}
	}
	return 0;
}

tarena@tedu:~$ g++ test.cpp
tarena@tedu:~$ ./a.out
index = 1, ipv4 =127.0.0.1
index = 2, ipv4 = 192.168.10.36

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值