当前位置:首页 > 芯闻号 > 充电吧
[导读]       想获取所有网卡的IP地址,但是遇到比如pppd拨号时候,网卡会是pp0,就会出现类似内存操作错误Segmentation fault,搜索谷歌,发现原因可能是At the moment

       想获取所有网卡的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 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#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 %dn",ret);

	printf("Following IP addresses are available:nn");
	for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
	{
		printf("Entry for ifa=%08xn",ifa);
		if (ifa ->ifa_addr->sa_family==AF_INET)
		{ // check it is IP4
			printf("ACTG: ipv4n");
			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: %st IP Address %sn", ifa->ifa_name, addressBuffer);
		}
		else if (ifa->ifa_addr->sa_family==AF_INET6)
		{ // check it is IP6
			printf("ACTG: ipv6n");
			// 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: %st IP Address %sn", ifa->ifa_name, addressBuffer);
		}
		printf("Leave for ifa=%08xn",ifa);
	}
	if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
	return 0;
}




本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除。
关闭
关闭