分割过错INET_NTOA [英] segmentation fault for inet_ntoa

查看:132
本文介绍了分割过错INET_NTOA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    #include <stdio.h> 
    #include <string.h> /* for strncpy */ 
    #include <sys/types.h> 
    #include <sys/socket.h> 
    #include <sys/ioctl.h> 
    #include <netinet/in.h> 
    #include <net/if.h> 

    int 
    main() 
    { 
     int fd;  
     struct ifreq ifr; 

     fd = socket(AF_INET, SOCK_DGRAM, 0);  

     /* I want to get an IPv4 IP address */ 
     ifr.ifr_addr.sa_family = AF_INET; 

     /* I want IP address attached to "eth0" */ 
     strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1); 

     ioctl(fd, SIOCGIFADDR, &ifr); 

     close(fd); 

     /* display result */ 
     char* ipaddr; 
     ipaddr = inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr); 
     printf("%s\n", ipaddr); 

     return 0; 
    } 

这条线:

     ipaddr = inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr);         

我得到

iptry.c: In function ‘main’:
iptry.c:31:9: warning: assignment makes pointer from integer without a cast [enabled by default]

     printf("%s\n", ipaddr);

我得到分段错误。

I get segmentation fault.

什么是错呢?

推荐答案

INET_NTOA 在头被定义&LT; ARPA / inet.h&GT; ,结果
需要的#include ,否则,会有误差

inet_ntoa is defined in the header <arpa/inet.h>,
need to #include, otherwise, there will be errors

这篇关于分割过错INET_NTOA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆