http://blog.csdn.net/weiyuefei/article/details/22198659
?之前項目原因,需要獲取當前服務器節點上所有網口的ip地址,但是當時由于時間比較緊,一直沒搞出來,最近沒那么忙了,又在網上找了一下,終于實現了這一個功能,因此記錄下來,以備不時之需。
??? 這種獲取所有ip的方法主要是通過遍歷所有網口信息而獲取的,即首先通過函數ioctl獲取所有網口的信息,然后再逐一遍歷每個網口,解析出網口對應的ip地址。下面是實現代碼是經過驗證的。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/types.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
//獲取地址
//返回IP地址字符串
//返回:0=成功,-1=失敗
int get_all_localip()
{
?int i = 0;
?int sockfd;
?struct ifconf ifconf;
?char buf[512];
?struct ifreq *ifreq;
?char *ip;
?//初始化ifconf
?ifconf.ifc_len = 512;
?ifconf.ifc_buf = buf;
?if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
?{
??return -1;
?}
?ioctl(sockfd, SIOCGIFCONF, &ifconf);??? //獲取所有接口信息
?close(sockfd);
?
?//接下來一個一個的獲取IP地址
?ifreq = (struct ifreq*)buf;
?for(i = (ifconf.ifc_len / sizeof(struct ifreq)); i > 0; i--)
?{
??ip = inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr);
??if(strcmp(ip,"127.0.0.1") == 0)? //排除127.0.0.1,繼續下一個
??{
???ifreq++;
???continue;
??}
??printf("IP地址: %s\n", ip);
??ip = NULL;
??ifreq++;
?}
?return 0;
}
int main() {
?get_all_localip();
?return 0;
}
?
以上參考:http://zhumeng8337797.blog.163.com/blog/static/1007689142012311082638/