2

Display a host IP address

  1. /*
  2.  * Calls gethostbyname and getservbyname and fills in a struct addr_in.
  3.  * Prints host IP address in dotted notation and as an int (network order
  4.  * and machine order) and the port number.
  5.  */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <errno.h>
  10. #if defined( LINUX )
  11. #include <string.h>
  12. #endif
  13.  
  14. #include <sys/socket.h>
  15. #include <netinet/in.h>
  16. #include <netdb.h>
  17.  
  18. int main( int argc, char **argv ) {
  19.     struct hostent *host;
  20.     struct servent *serv;
  21.  
  22.     struct sockaddr_in addr;
  23.  
  24.     char *hostname;
  25.     char *servname;
  26.     char *protname;
  27.  
  28.     switch ( argc ) {
  29.     case 4:
  30.         hostname = argv[1];
  31.         servname = argv[2];
  32.         protname = argv[3];
  33.         break;
  34.     default:
  35.         usage: fprintf( stderr, "%s hostname servname proto\n", argv[0] );
  36.         exit( 1 );
  37.     }
  38.  
  39.     if ( (serv = getservbyname( servname, protname )) == 0 ) {
  40.         fprintf( stderr, "Service not found\n" ); /* errno == 0 ! */
  41.         return -1;
  42.     }
  43.     endservent();
  44.  
  45.     if ( (host = gethostbyname( hostname )) == 0 ) {
  46.         fprintf( stderr, "Host not found\n" ); /* errno == 0 ! */
  47.         return -1;
  48.     }
  49.     endhostent();
  50.  
  51.     addr.sin_family = AF_INET;
  52.     addr.sin_addr.s_addr = *((unsigned *) host->h_addr);
  53.     addr.sin_port = serv->s_port; /* already in network order */
  54.  
  55.     printf( "%u.%u.%u.%u 0x%x (0x%x) %d (%d)\n", ((unsigned char *) &addr.sin_addr.s_addr)[0],
  56.             ((unsigned char *) &addr.sin_addr.s_addr)[1], ((unsigned char *) &addr.sin_addr.s_addr)[2],
  57.             ((unsigned char *) &addr.sin_addr.s_addr)[3],
  58.             addr.sin_addr.s_addr,           /* network order */
  59.             ntohl( addr.sin_addr.s_addr ),  /* machine order */
  60.             addr.sin_port,                  /* network order */
  61.             ntohs( addr.sin_port ) );       /* machine order */
  62.  
  63.     exit( 0 );
  64. }

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].