sockets - C - Get a string of an IP address using sin_addr -
this question has answer here:
- how print ip address getaddrinfo() 2 answers
i'm trying ip address struct in_addr
, put in char
array. i've tried following code got segmentation fault error.
char ip[30]; strcpy(ip, (char*)inet_ntoa((struct in_addr)clt.sin_addr));
can tell me how fix this?
expanded code bit make compile
#include <netinet/in.h> struct sockaddr_in clt; int main() { char ip[30]; strcpy(ip, (char*)inet_ntoa((struct in_addr)clt.sin_addr)); }
trying compile warning enabled (always idea) gives few warnings, , sure not work
$ gcc -wall -wextra -o3 ntoa.c -o ntoa && ./ntoa ntoa.c: in function 'main': ntoa.c:5:3: warning: implicit declaration of function 'strcpy' [-wimplicit-function-declaration] ntoa.c:5:3: warning: incompatible implicit declaration of built-in function 'strcpy' [enabled default] ntoa.c:5:3: warning: implicit declaration of function 'inet_ntoa' [-wimplicit-function-declaration] ntoa.c:5:14: warning: cast pointer integer of different size [-wint-to-pointer-cast] ntoa.c:6:1: warning: control reaches end of non-void function [-wreturn-type] segmentation fault $
including headers missing function declarations @ top (always idea too)
#include <arpa/inet.h> #include <string.h>
apparently fixes it:
$ gcc -wall -wextra -o3 ntoa.c -o ntoa && ./ntoa ntoa.c: in function 'main': ntoa.c:8:1: warning: control reaches end of non-void function [-wreturn-type] $
Comments
Post a Comment