10
Afficher l'adresse IP d'une machine
- /*
- * Calls gethostbyname and getservbyname and fills in a struct addr_in.
- * Prints host IP address in dotted notation and as an int (network order
- * and machine order) and the port number.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #if defined( LINUX )
- #include <string.h>
- #endif
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netdb.h>
- int main( int argc, char **argv ) {
- struct hostent *host;
- struct servent *serv;
- struct sockaddr_in addr;
- char *hostname;
- char *servname;
- char *protname;
- switch ( argc ) {
- case 4:
- hostname = argv[1];
- servname = argv[2];
- protname = argv[3];
- break;
- default:
- usage: fprintf( stderr, "%s hostname servname proto\n", argv[0] );
- exit( 1 );
- }
- if ( (serv = getservbyname( servname, protname )) == 0 ) {
- fprintf( stderr, "Service not found\n" ); /* errno == 0 ! */
- return -1;
- }
- endservent();
- if ( (host = gethostbyname( hostname )) == 0 ) {
- fprintf( stderr, "Host not found\n" ); /* errno == 0 ! */
- return -1;
- }
- endhostent();
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = *((unsigned *) host->h_addr);
- addr.sin_port = serv->s_port; /* already in network order */
- printf( "%u.%u.%u.%u 0x%x (0x%x) %d (%d)\n", ((unsigned char *) &addr.sin_addr.s_addr)[0],
- ((unsigned char *) &addr.sin_addr.s_addr)[1], ((unsigned char *) &addr.sin_addr.s_addr)[2],
- ((unsigned char *) &addr.sin_addr.s_addr)[3],
- addr.sin_addr.s_addr, /* network order */
- ntohl( addr.sin_addr.s_addr ), /* machine order */
- addr.sin_port, /* network order */
- ntohs( addr.sin_port ) ); /* machine order */
- exit( 0 );
- }
Commentaires