Operating System - HP-UX
1753341 Members
4968 Online
108792 Solutions
New Discussion юеВ

Re: how to get current host's hostname by gethostname?

 
SOLVED
Go to solution
apache
New Member

how to get current host's hostname by gethostname?

I don't know how to use gethostname(),Do anyone can help me? Thanks!!!
Please give me a sample about gethostname().
3 REPLIES 3
Deepak Extross
Honored Contributor
Solution

Re: how to get current host's hostname by gethostname?

Few things to remember:
1. Include
2. Allocate sufficient space for the hostname. For example, declare char chHostName[50]
You can get the max hostname from /usr/include/sys/param.h - look for MAXHOSTNAMELEN
3. If the return value is not 0, check the errno for dagnostics.
Peter Kloetgen
Esteemed Contributor

Re: how to get current host's hostname by gethostname?

Hi,

gethostname() is a system call used by other commands to get the hostname:

uname
sethostname
hostname

to get the hosts hostname, use simply

# hostname
--> name_of_host is the output

Allways stay on the bright side of life!

Peter
I'm learning here as well as helping
Joseph A Benaiah_1
Regular Advisor

Re: how to get current host's hostname by gethostname?

Here is an example program using gethostname() called gethost.c

#include
#include

main()
{
char hostname[64];

if (gethostname(hostname, sizeof(hostname)) < 0)
{
perror("gethostname");
exit(1);
}
else
{
fprintf(stdout, "HOSTNAME = %s\n", hostname);
}

exit(0);
}

Hope this helps.

Cheers,

Joseph.