这是一个套接字通信的服务器。当客户端向服务器发送 URL 时,服务器将 IP 发送给客户端。当它运行时hptr = gethostbyname(buffer)
,它总是返回NULL
。为什么?谢谢!
#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;
}