c - Segmentation fault while trying to print name by passing ip (getnameinfo) -
i can't handle it, can't see what's wrong code.
trying print name (of site suspect) ip, can't 3 days, it's depressing me.
so, code:
/** * task1.c -- getnameinfo() usage example * * copyright (c) 2014 ovchinnikov alexzander * * code licensed under mit-style license. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <arpa/inet.h> #include <locale.h> /** * main * @param argv количество параметров командной строки (учитая имя программы) * @param argv массив строк-параметров командной строки */ int main(int argc, char *argv[]) { int result; struct sockaddr_in *sa; /* input */ char hbuf[ni_maxhost]; /* * Инициализация подсистемы locale */ (void) setlocale(lc_all, ""); /* * Должен быть один и только один аргумент командной строки */ if (2 != argc) { fprintf(stderr, "usage: %s ipv4 address\n", argv[0]); exit(exit_failure); } /* * Что-то делаем */ sa->sin_family = af_inet; sa->sin_port = htons(80); result = inet_pton(af_inet, argv[1], &(sa->sin_addr)); if (result <= 0){ if (result == 0){ fprintf(stderr, "not in presentation format"); }else{ perror("inet_pton"); exit(exit_failure); } } memset(&sa->sin_zero, '\0', sizeof(sa->sin_zero)); /* * Получить имя для адреса в argv[1] */ if (0 != (result = getnameinfo((struct sockaddr *)sa, sizeof(sa), hbuf, sizeof(hbuf), null, 0, ni_namereqd))){ fprintf(stderr, "getnameinfo() error: %s\n", gai_strerror(result)); }else{ fprintf(stdout, "host:%s\n", hbuf); } return 0; }
when compiling:
gcc -wall -o task1_2 task1_2.c
, this:
task1_2.c:49:20: warning: ‘sa’ may used uninitialized in function [-wmaybe-uninitialized] sa->sin_family = af_inet;
and when running this:
./task1_2 87.240.131.120
, segmentation fault.
you haven't allocated memory sa
sa = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
Comments
Post a Comment