Be sure you know the uses of gethostbyname(), inet_ntoa()
and inet_addr().
- gethostbyname()
- returns struct hostent*
- takes argument like "sun13.cs.wisc.edu"
- inet_addr()
- returns unsigned long
- takes argument like "128.105.40.13"
- inet_ntoa()
- returns char * pointing to something like "128.105.40.13"
- takes struct in_addr as an argument
Example of using gethostbyname():
struct hostent* server;
struct sockaddr_in destAddr;
/* argv[1] is "sun13.cs.wisc.edu" */
if ( (server = gethostbyname(argv[1])) == NULL )
{
fprintf(stderr, "Cannot get address for host %s\n", argv[1]);
exit(1);
}
memcpy(&(destAddr.sin_addr.s_addr), server->h_addr, server->h_length);
Example of using inet_addr():
struct sockaddr_in destAddr;
destAddr.sin_addr.s_addr = inet_addr("128.105.40.13");
Example of using inet_ntoa():
// if added to the above inet_addr() code, this would print "128.105.40.13":
//
char *s = inet_ntoa(destAddr.sin_addr);
printf("dotted decimal address is %s\n", s);