Host IP address
Hello all!
Sometimes is useful to know the IP address of the machine we are working on, for example when we connect a SMTP server and do the EHLO <domain> command. I have written a short C++ program that first prints the host name and the host IP address, then if arguments from command line are passed prints the IP address of each domain name.
/* IPadress.cpp
Author: HIToC
*/
#include <iostream.h>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <string>
#include <stdio.h>
int main(int argc, char* argv[])
{
hostent *hh;
string IP, my_name;
char* host_name = new char[64];
gethostname(host_name, 64);
my_name = host_name;
cout <<"Host name:\t\t" <<my_name <<'\n';
hh = gethostbyname(host_name);
IP = inet_ntoa(*((struct in_addr *)hh->h_addr));
cout <<"My IP address:\t\t" <<IP <<"\n\n";
for(int i = 1; i<argc; i++) {
hh = gethostbyname(argv[i]);
if(hh == NULL) {
cerr <<"Error with \"" <<argv[i] <<"\" !\n";
continue;
}
IP = inet_ntoa(*((struct in_addr *)hh->h_addr));
cout <<"IP address of " <<argv[i] <<" :\t" <<IP <<'\n';
}
return 0;
}If called without any parameter, the output is always:
Host name: linux
My IP address: 127.0.0.2
If like argument I pass localhost, thw output is:
Host name: linux
My IP address: 127.0.0.2
IP address of localhost: 127.0.0.1
My intent is to know my real IP address!
Can anybody help me?
Thaks for any suggestion.
Signature · 5 lines
With regards, HIToC [email protected]
Quoted 7 lines · HIToC
Sometimes is useful to know the IP address of the machine we are working on, for example when we connect a SMTP server and do the EHLO <domain> command. I have written a short C++ program that first prints the host name and the host IP address, then if arguments from command line are passed prints the IP address of each domain name.
My intent is to know my real IP address!
A system may have any number of IP addresses, including zero. You can't assume that there is exactly one IP address.
Also, the results obtained from gethostname() and gethostbyname() aren't necessarily correct. That just tells you what your hostname resolves to using whatever name resolution method(s) your system is configured to use (e.g. /etc/hosts, DNS, NIS etc).
If you want to determine the IP addresses of any local interfaces, first obtain a list of interfaces by either calling ioctl(SIOCGIFCONF) or parsing /proc/net/dev. Then call ioctl(SIOCGIFADDR) for each interface to obtain its address. See the source code for "ifconfig" (from the net-tools package) for more details.
Signature · 1 line
Glynn Clements <[email protected]>