#include #include // for perror #include // for gethostbyname #include // for errno #include // for strcpy using namespace std; const int BUF_SIZE = 256; int main() { char name[BUF_SIZE]; int errorSave; cout << "This one should be a success " << endl; // an example of success if (-1 == gethostname(name, BUF_SIZE)) { cout << "Failed to get the host name " << endl; } else { cout << "The host name is " << name << endl; } cout << endl; cout << "This should fail" << endl; // try again, but this time, don't admit we have sufficient space. if (-1 == gethostname(name, 0)) { cout << "Failed to get the host name " << endl; } else { cout << "The host name is " << name << endl; } cout << "errno is " << errno << endl; cout << endl; cout << "Try again, with perror " << endl; if (-1 == gethostname(name, 0)) { errorSave = errno; perror("gethostbyename failed"); strcpy(name, "UNKNOWN"); } cout << "The host name is " << name << endl; // get the error message and display it. cout <<"By the way, that error was \"" << strerror(errorSave) <<"\"" << endl; cout << endl; cout << "Just for fun, let's try to set the hostname" << endl; if(-1 == sethostname("newname",sizeof("newname")-1) ) { perror("sethostname() failed"); } cout << "Drat, knew it!" << endl; return 0; }