Ho il seguente pezzo di codice per ottenere il nome host e l'indirizzo IP,Segmentation fault quando si cerca su nome host e l'indirizzo IP
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h> /* This is the header file needed for gethostbyname() */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
struct hostent *he;
if (argc!=2){
printf("Usage: %s <hostname>\n",argv[0]);
exit(-1);
}
if ((he=gethostbyname(argv[1]))==NULL){
printf("gethostbyname() error\n");
exit(-1);
}
printf("Hostname : %s\n",he->h_name); /* prints the hostname */
printf("IP Address: %s\n",inet_ntoa(*((struct in_addr *)he->h_addr))); /* prints IP address */
}
Ma io sono sempre un avviso durante la compilazione:
$cc host.c -o host
host.c: In function ‘main’:
host.c:24: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
Poi c'è un errore di segmentazione quando si esegue il codice:
./host 192.168.1.4
Hostname : 192.168.1.4
Segmentation fault
Qual è l'errore nel codice?
Stai facendo qualcosa di orribile a una struttura innocente. – SLaks
A proposito, in generale non si dovrebbe usare 'gethostbyname' nel nuovo codice, soprattutto perché non è compatibile con IPv6. Dovresti invece usare 'getaddrinfo': http://beej.us/guide/bgnet/output/html/multipage/getaddrinfoman.html –
Cosa succede se esegui ./host www.stackoverflow.com? Cioè, se lo usi con un nome reale piuttosto che un indirizzo IP. – nsayer