linux C如何获取服务器节点上所有网口的ip地址
http://blog.csdn.net/weiyuefei/article/details/22198659
?之前項(xiàng)目原因,需要獲取當(dāng)前服務(wù)器節(jié)點(diǎn)上所有網(wǎng)口的ip地址,但是當(dāng)時(shí)由于時(shí)間比較緊,一直沒(méi)搞出來(lái),最近沒(méi)那么忙了,又在網(wǎng)上找了一下,終于實(shí)現(xiàn)了這一個(gè)功能,因此記錄下來(lái),以備不時(shí)之需。
??? 這種獲取所有ip的方法主要是通過(guò)遍歷所有網(wǎng)口信息而獲取的,即首先通過(guò)函數(shù)ioctl獲取所有網(wǎng)口的信息,然后再逐一遍歷每個(gè)網(wǎng)口,解析出網(wǎng)口對(duì)應(yīng)的ip地址。下面是實(shí)現(xiàn)代碼是經(jīng)過(guò)驗(yàn)證的。
#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);
?
?//接下來(lái)一個(gè)一個(gè)的獲取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,繼續(xù)下一個(gè)
??{
???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/
總結(jié)
以上是生活随笔為你收集整理的linux C如何获取服务器节点上所有网口的ip地址的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 结扎后想要孩子还可以接吗
- 下一篇: 使命召唤远射勋章怎么获得