LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   [code]gethostbyaddr() unknown host (https://www.linuxquestions.org/questions/linux-newbie-8/%5Bcode%5Dgethostbyaddr-unknown-host-703419/)

Jane2008 02-09-2009 02:32 PM

[code]gethostbyaddr() unknown host
 
I need to communicate with a monitor module. The IP of it is 192.168.0.100 and the port is 8080.
The ping 192.168.0.100 works well.
The socket is created successfully but the gethostbyaddr()failed.
Would anyone help to look into it? Thanks.
int main( int argc, char **argv )
{
char buffer[4096];
struct hostent *hostaddr;
int port=8080;
struct protoent *protocol;
int rval;
int sd;
struct sockaddr_in socketaddr;
char *ptr="192.168.0.100";

protocol = getprotobyname( "tcp" );
if ( !protocol )
{ perror( "getprotobyname()" );
return (errno);
}
sd = socket( PF_INET, SOCK_STREAM, protocol->p_proto );
if ( sd == -1 )
{ perror( "socket()" );
return (errno);
}

memset( &socketaddr, 0, sizeof(socketaddr) );
socketaddr.sin_family = AF_INET;
socketaddr.sin_port = htons( port );
socketaddr.sin_addr.s_addr = inet_addr(ptr);

hostaddr = gethostbyaddr((char *)socketaddr.sin_addr.s_addr), 4, AF_INET);
if ( !hostaddr )
{ fprintf( stderr, "gethostbyname(): %s\n", hstrerror(h_errno) );
return (h_errno);
}
memcpy( &socketaddr.sin_addr, hostaddr->h_addr, hostaddr->h_length );
rval = connect( sd, (struct sockaddr *) &socketaddr, sizeof(socketaddr) );
if ( rval == -1 )
{ perror( "connect()" );
return (errno);
}
rval = recv( sd, buffer, sizeof(buffer), 0 );
if ( rval == -1 )
{ perror( "recv()" ); }
else
{ fwrite( buffer, rval, 1, stdout ); }
close( sd );
return (0);
}

Jane2008 02-09-2009 03:49 PM

I tried to skip the gethostbyaddr() and use connect() directly. It still failed with timeout.

Jane2008 02-10-2009 01:41 PM

If i reset the monitor module, the connect() works. The problem is when the program is finished, the connection isn't released, i.e, the close() doesn't work. Actually, I add one printf under the close(), it works. I don't know why. Is there any function used to release the socket? Thanks.

Jane2008 02-10-2009 01:52 PM

I knew how to solve it.
shutdown() shall be used to shut down the socket.


All times are GMT -5. The time now is 06:28 AM.