#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;
}
for this line:
ipaddr = inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr);
I get
iptry.c: In function ‘main’:
iptry.c:31:9: warning: assignment makes pointer from integer without a cast [enabled by default]
and for
printf("%s\n", ipaddr);
I get segmentation fault.
What is wrong with this?
inet_ntoa
is defined in the header <arpa/inet.h>
,
need to #include
, otherwise, there will be errors
inet_ntoa
does not demand a pointer, but value
char* ipaddr;
ipaddr = inet_ntoa(((struct sockaddr_in)(ifr.ifr_addr))->sin_addr);
If sin_addr
is a pointer, you'll need to dereference it.
inet_ntoa
will return NULL
if there is an error, so trying to printf
a NULL will cuase a segmentation fault...
If you don't want to see the warning, just cast the return value of inet_ntoa
ipaddr = (char *) inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr);
The segmentation fault is probably because some of the previous function returns an error (null value) and you didn't check it
The same code worked in my Linux Box.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.