Operating System - HP-UX
1822728 Members
3764 Online
109644 Solutions
New Discussion юеВ

How to put hostname in a variable in a C program ?

 
SOLVED
Go to solution
Michel PIGUEL
Occasional Advisor

How to put hostname in a variable in a C program ?

Hello,
In a C program, I would like to put the server hostname (and more generally the result of a shell command) in a variable. I can show it on stdout with the following piece of program but I can't store it:

main()
{
char nodeName[9];
system("/usr/bin/hostname");
exit(0);
}

M.Piguel
4 REPLIES 4
Ralph Grothe
Honored Contributor

Re: How to put hostname in a variable in a C program ?

Have a look at the standard C lib functions gethost*()

e.g.

man gethostent
Madness, thy name is system administration
Ralph Grothe
Honored Contributor

Re: How to put hostname in a variable in a C program ?

Forgot the 2nd part of your question, howto catch output from system commands.
I assume this is more involved in C (I'm no C hacker, only do things in Perl, but the principle, as Perl inherited almost all from the standard C libs, should be the same)
For this I guess you will have to fork, open a pipe, and do an exec* with the system command in the child's part, and read the output in the parent's part from the pipe's reader handle.
I could code this easily in Perl, but as said not in C, so please also have a look at the manpages of
fork
exec
pipe
Madness, thy name is system administration
Ceesjan van Hattum
Esteemed Contributor

Re: How to put hostname in a variable in a C program ?

Maybe not exactly what you want, but environment variables can be put into local-vars of c, like:

#include
envvar=getenv("TERM");
printf("The value for the environment variable TERM is ");
if(envvar)
{ printf("%s\n",envvar); }
else { printf("not set.\n"); }
}

Unfortunately, HOSTNAME is in most cases not a environment variable, but maybe you can set it yourself: export HOSTNAME=`uname -n`.

Regards,
Ceesjan
James R. Ferguson
Acclaimed Contributor
Solution

Re: How to put hostname in a variable in a C program ?

Hi:

You can use 'gethostname'. Crudely:

#include
main()
{
char hostname[9];
gethostname(hostname,9);
printf("%s %s\n","I am host",hostname);
exit(0);
}

Regards!

...JRF...