How to permanently modify hostname under Linux

 

For our terminal device, connect to wifi, we want to distinguish the device name, then it is a better choice to modify the hostname, for the hostname, we can pass

man hostname to view related content;

If we want to check the hostname of the current system, we can use the following command:

(1)  uname -n

(2)  hostname

We can modify the hostname by command:

hostname mydefinename 

What we modify through instructions is actually the content in /proc/sys/kernel/hostname;

Similarly, we can also use the system's API calls:

The code is as follows: hostname_main.cpp

#include <unistd.h>
#include <stdio.h>
#include<string.h>

int main()
{
    char buf[50] = "localhost.localdomain";

    if (sethostname(buf, strlen("localhost.localdomain")) < 0)
    {
        perror("sethostname");
    }
    else
    {
        printf("sethostname success!\n");
    }
     char buff[50];

    if (gethostname(buff, sizeof(buff)) == 0)
    {
        printf("%s\n", buff);
    }
    else
    {
        perror("gethostname");
    }
 return 0;
}

Compile:

 g++ -o hostname_main hostname_main.cpp

The execution results are as follows:

[root@localhost Test307]# ./hostname_main 
sethostname success!
localhost.localdomain
[root@localhost Test307]# 

 

Guess you like

Origin blog.csdn.net/Swallow_he/article/details/107490439