0

I'm trying get an IP address from struct in_addr and put it in a char array. I've tried the following code but I got the segmentation fault error.

char ip[30];
strcpy(ip, (char*)inet_ntoa((struct in_addr)clt.sin_addr));

Can anyone tell me how to fix this?

user
  • 85
  • 3
  • 13

1 Answers1

2

Expanded your code a bit to make it 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 to compile it with warning enabled (always a good idea) gives a few warnings, and it sure does 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 by default]
ntoa.c:5:3: warning: implicit declaration of function 'inet_ntoa' [-Wimplicit-function-declaration]
ntoa.c:5:14: warning: cast to pointer from 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 the headers with the missing function declarations at the top (always a good 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]
$