ip-adresse(n) ermitteln

Post Reply
Message
Author
Descartes

ip-adresse(n) ermitteln

#1 Post by Descartes »

Mit folgendem Programm kann ich den FullQualifiedHostname und die zugehörige IP-Adresse ermitteln.
Wie kann ich allerdings bei einem Rechner der mehrere Netzwerkkarten hat alle IP-Adressen ermitteln ?

Konkret habe ich hier einen Rechner mit zwei Netzwerkkarten.
Wenn ich das Programm aufrufe erhalte ich nur eine der beiden IP-Adressen zurück.
Die erste Idee, dass in hostent_ptr->h_addr_list alle möglichen IP-Adressen des Rechner abgelegt scheint falsch zu sein. Wenn ich mit hostent_ptr->h_addr_list[<!--no-->1<!--no-->] zum Beispiel auf die zweite IP-Adresse zugreifen möchte erhalte ich nur einen core-dump.

Gebt's ihr mir doch mal einen Denkanstoss.

<blockquote><pre><font size="1" face="">code:</font><hr><font face="Courier New" size="2">
/*
* linux:~ $ man --apropos gethostname
* gethostname (2) - get/set host name
*
* linux:~ $ man --apropos gethostbyname
* gethostbyname (3) - get network host entry
*
* linux:~ $ man --apropos inet_ntoa
* inet_ntoa (3) - Internet address manipulation routines
* inet_ntoa (3pm) [Socket] - load the C socket.h defines and structure manipulators
*
*/

#include <arpa/inet.h> // inet_ntoa()
#include <iostream> // cout, endl
#include <netdb.h> // gethostbyname(char*)
#include <netinet/in.h>
#include <unistd.h> // gethostname(char*,int)
#include <sys/socket.h> // AF_INET
#include <sys/types.h>

#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 255
#endif

using namespace std;

int main(int argc, char** argv)
{
char hostnamebuffer[MAXHOSTNAMELEN];
int rc;
struct hostent *hostent_ptr;
in_addr ia;

if (argc == 2)
{
strcpy( hostnamebuffer, argv[<!--no-->1<!--no-->] );
}
else
{
rc = gethostname( hostnamebuffer, MAXHOSTNAMELEN );

if (rc != 0)
{
cerr << "gethostname() failed." << endl;
return 1;
}
}

hostent_ptr = gethostbyname( hostnamebuffer );

if (hostent_ptr == 0)
{
cerr << "gethostbyname() failed." << endl;
return 1;
}

memcpy( (void*)&ia, (void*)hostent_ptr->h_addr_list[<!--no-->0<!--no-->], hostent_ptr->h_length );

cout << " hostname = " << hostnamebuffer << endl;
cout << "full qualified hostname = " << hostent_ptr->h_name << endl;
cout << " ip address = " << inet_ntoa(ia) << endl;

return 0;
}
</font><hr></pre></blockquote>

Post Reply