想获取所有网卡的IP地址,但是遇到比如pppd拨号时候,网卡会是pp0,就会出现类似内存操作错误Segmentation fault,搜索谷歌,发现原因可能是At the moment it finds PPP interfaces, but does not return the destination address.就是说,如果找到的是PPP设备,返回的地址就可能为空,这样继续打印对应的IP地址就会出错。
kill掉pppd进程以后,再运行获取IP地址,就正常了,貌似是个bug,但是如何解决呢?
基本代码如下:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/if_link.h>
#define INET_ADDRSTRLEN 16
#define INET6_ADDRSTRLEN 46
int main(void)
{
struct ifaddrs * ifAddrStruct=NULL;
struct ifaddrs * ifa=NULL;
int ret=0;
ret=getifaddrs(&ifAddrStruct);
printf("End getifaddrs %d\n",ret);
printf("Following IP addresses are available:\n\n");
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
{
printf("Entry for ifa=%08x\n",ifa);
if (ifa ->ifa_addr->sa_family==AF_INET)
{ // check it is IP4
printf("ACTG: ipv4\n");
void * tmpAddrPtr=NULL;
// 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(" IPv4: interface: %s\t IP Address %s\n", ifa->ifa_name, addressBuffer);
}
else if (ifa->ifa_addr->sa_family==AF_INET6)
{ // check it is IP6
printf("ACTG: ipv6\n");
// is a valid IP6 Address
char addressBuffer[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, (void*)&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr, addressBuffer, INET6_ADDRSTRLEN);
printf(" IPv6: interface: %s\t IP Address %s\n", ifa->ifa_name, addressBuffer);
}
printf("Leave for ifa=%08x\n",ifa);
}
if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
return 0;
}
本文介绍了一个在使用pppd拨号时获取网卡IP地址过程中遇到的问题及解决方案。当程序尝试从PPP设备获取IP地址时会出现段错误,通过终止pppd进程可以避免此问题。文章提供了基础代码示例并探讨了解决方案。
705

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



