Tuesday, August 23, 2011

Using the uname(2) Function - socket

One useful function to know about is the uname(2) function. This function tells your program a little bit about the system in which it is executing. The function prototype for this function is as follows:

#include <sys/utsname.h>
int uname(struct utsname *buf);

The function returns information into the structure buf. The value returned is zero when successful, or -1 when an error is reported. External variable errno will contain the reason for the error.

The struct utsname is defined as follows:

#include <sys/utsname.h> /* defines the following structure */

struct utsname {
   char sysname[SYS_NMLN];
   char nodename[SYS_NMLN];
   char release[SYS_NMLN];
   char version[SYS_NMLN];
   char machine[SYS_NMLN];
   char domainname[SYS_NMLN];

The structure members are described in detail in Table below:

This represents the operating system being used. For Linux, this
value is the C string "Linux".
This represents the machine's network node hostname.
The operating system release. For example, the C string "2.2.10"
is returned for kernel release 2.2.10
The operating system version. For Linux, this represents the version
number, date, and time stamp of the kernel build.
This represents the hardware type of the host. For example, "i686"
represents a Pentium CPU.
This returns the NIS/YP domain name for the host.

NIS/YP (Network Information Service) is beyond the scope of this book. NIS provides centralized information management for a group of hosts in a network. It permits a centralized management of users, groups, and passwords, for example.

A simple program to permit you to test the values returned by uname(2) is shown in Listing below This program invokes uname(2) and then displays the contents of the information it has returned
in the structure utsname.

 /* uname.c:
  * Example of uname(2):
  #include <stdio.h>
  #include <unistd.h>
  #include <stdlib.h>
  #include <errno.h>
  #include <string.h>
  #include <sys/utsname.h>

  int main(int argc,char **argv) {
     int z;
     struct utsname u_name;

     z = uname(&u_name);

     if ( z == -1 ) {
        fprintf(stderr, "%s: uname(2)\n",

     printf(" sysname[]   = '%s';\n", u_name.sysname);
     printf(" nodename[]  = '%s';\n", u_name.nodename);
     printf(" release[]   = '%s';\n", u_name.release);
     printf(" version[]   = '%s';\n", u_name.version);
     printf(" machine[]   = '%s';\n", u_name.machine);
     return 0;
 [sgupta@rhel55x64 socket]$ gcc uname.c –o uname
 [sgupta@rhel55x64 socket]$ ./uname
 sysname[]  = 'Linux';
 nodename[] = 'rhel55x64';
 release[]  = '2.6.18-164.el5';
 version[]  = '#1 SMP Tue Aug 18 15:51:48 EDT 2009';
 machine[]  = 'x86_64';
 [sgupta@ rhel55x64 socket]$

No comments:

Post a Comment