关于gethostbyaddr
我想写一个小程序用来检测局域网内主机名,稍微改了一下先在自己机子上运行看是否显示自己的主机名
struct sockaddr_in my_addr,cli_addr,br_addr;
char *part= "*** ";
int sockfd,connfd,len,n,slen;
void *th_do(void *arg)
{
while(1)
sendto(sockfd,part,3,0,(struct sockaddr*)&br_addr,sizeof(br_addr));
}
main()
{
char readbuf[max];
struct hostent *hptr;
pthread_t tid;
if((sockfd=socket(AF_INET,SOCK_DGRAM,0)) <0)
{
fprintf(stderr, "socket err!\n ");
exit(1);
}
bzero(&(my_addr),sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVER_PORT);
my_addr.sin_addr.s_addr=INADDR_ANY;
bzero(&(br_addr),sizeof(br_addr));
br_addr.sin_family=AF_INET;
br_addr.sin_port=htons(SERVER_PORT);
inet_aton( "10.17.5.255 ",&br_addr.sin_addr);
if(bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr)) <0)
{
fprintf(stderr, "bind err!\n ");
exit(1);
}
int bBroadcast=1000;
if((setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,(const char*)&bBroadcast,sizeof(int)))==-1)
printf( "set error!\n ");
pthread_create(&tid,NULL,th_do,NULL);
len=sizeof(cli_addr);
while(1)
{
if((n=recvfrom(sockfd,readbuf,max,0,(struct sockaddr*)&(cli_addr),(void *)&len))> 0)
{
printf( "OK!\n ");
readbuf[n]= '\0 ';
if(strcmp(readbuf,part)==0)
{
slen=sizeof(cli_addr.sin_addr);
if(!(hptr=gethostbyaddr(&(cli_addr.sin_addr),slen,AF_INET)))
printf( "get error!\n ");
else printf( "%s\n ",errno);
}
}
}
}运行老是get error,看来是gethostbyaddr返回空的问题。。。
这是怎么回事?
------解决方案--------------------try it
if(!(hptr=gethostbyaddr(&(cli_addr.sin_addr),&slen,AF_INET)))