This is the server of a socket communication. When the client sends a URL to the server, the server sends the IP to client. When it runs hptr = gethostbyname(buffer)
, it always returns NULL
. Why? Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
int main( int argc, char *argv[] )
{
int sockfd, streamfd, addr_size, status;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
struct in_addr **addr_list;
struct hostent *hptr;
char *ptr, **pptr;
char str[32];
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");
exit(1);
}
/* Initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = PF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(1234);
/* Now bind the host address using bind() call.*/
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
perror("ERROR on binding");
exit(1);
}
/* Now start listening for the clients, here process will
* go in sleep mode and will wait for the incoming connection
*/
listen(sockfd,10);
addr_size = sizeof(cli_addr);
/* Accept actual connection from the client */
while(1){
streamfd = accept (sockfd, (struct sockaddr *) &cli_addr, &addr_size);
status = read (streamfd, buffer, 255);
printf ("string from net: %s\n", buffer);
if((hptr = gethostbyname(buffer)) == NULL)
{
printf("gethostbyname error for host:%s\n", buffer);
return 0;
}
printf("IP Address:%s\n",inet_ntoa(*((struct in_addr *)hptr->h_addr)));
close(streamfd);
}
return 0;
}
the posted code doesn't even come close to compiling.
Strongly suggest when compiling to enable all warnings
(for gcc, as a minimum, '-Wall -Wextra -pedantic')
Then fix the warnings.
please consistently indent the code, for readability by us humans
many system functions return a value that can be used to determine if the operation was successful. read() is such a function.
The code needs to perform error checking on the returned value from read()