#include <stdio.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <stdlib.h>
#include <time.h>
#include <sys/vfs.h>
#include <stdio.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main (int argc, const char * argv[])
{
struct ifaddrs * ifAddrStruct=NULL;
void * tmpAddrPtr=NULL;
getifaddrs(&ifAddrStruct);
while (ifAddrStruct!=NULL)
{
if (ifAddrStruct->ifa_addr->sa_family==AF_INET)
{ // check it is IP4
// is a valid IP4 Address
tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
printf("%s IPV4 Address %s\n", ifAddrStruct->ifa_name, addressBuffer);
}
else if (ifAddrStruct->ifa_addr->sa_family==AF_INET6)
{ // check it is IP6
// is a valid IP6 Address
tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
char addressBuffer[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
printf("%s IPV6 Address %s\n", ifAddrStruct->ifa_name, addressBuffer);
}
ifAddrStruct = ifAddrStruct->ifa_next;
}
return 0;
}
编译
gcc -g -O0 -o showip main.c
执行
./showip
显示如下
[root@localhost ~]# ./showip
lo IPV4 Address 127.0.0.1
eth0 IPV4 Address 192.168.1.103
lo IPV6 Address ::
eth0 IPV6 Address 0:0:fe80::20c:29ff
本文介绍了一个简单的C程序,用于枚举并打印出系统中所有网络接口的IPv4和IPv6地址。通过调用getifaddrs函数获取网络接口信息,并使用inet_ntop函数将网络地址转换为可读字符串。
388

被折叠的 条评论
为什么被折叠?



