/**/ How to get OS version in C? - Dextutor Programs

How to get OS version in C?

In this post we are going to solve a common question that dazzles most programmers – How to get OS version in C? When building an application sometimes a requirement is to check the operating system version. Programmers find it difficult to achieve this in C language.

The solution to the above question is using the uname system call. The syntax of uname system call is

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

First of all, we require a variable for structure utsname. The uname system call takes this variable name as its input. The definition of utsname is in header file sys/utsname.h. On success, name returns ‘0’ while on failure it returns -1. This structure contains the following different types of information.

utsname structure
Members
Detail
char sysname[]The operating system name
char nodename[]the host name
char release[]operating system release
char version[]operating system version
char machine[]the hardware type

A programmer can extract any information as per requirement from the utsname structure. For example, the below program will print the following details:
operating system name
hardware type
release
version

#Program to print the OS name, hardware used, release information and version of OS.

#include<sys/utsname.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
struct utsname uts;
uname(&uts);
printf("System is %s on %s hardware\n",uts.sysname, uts.machine);
printf("OS Release is %s\n",uts.release);
printf("OS Version is\n",uts.version);
}

Output

how to get os version in C

How it works?

The program calls uname function with uts as its parameter. uname returns the system information in the structure uts. Next, the programs print the system name, hardware type, release, and finally, the version of the operating system.

If you want to print the machine’s network name, then use the gethostname() function. The syntax of gethostname() function is

#include<unistd.h>
int gethostname(char *name, size_t namelen);

On success, gethostname returns 0 and the systems hostname is stored in variable name. On failure, it returns -1.

#include<unistd.h>
#include<stdio.h>
int main()
{
char comp[256];
gethostname(comp, 255);
printf("Computer host name is %s\n", comp);
}

Output

$ ./a.out
Computer host name is ocean

How it works?

The program calls gethostname() function which returns the network name. For instance, in this case, the network name of the system is ocean.

To change the hostname of the system sethostname() function can be used.


1 thought on “How to get OS version in C?”

Leave a Comment