Cisco,SHELL,Qt,C++,Linux,ネットワーク,Windows Scriptなどの発言です

Linux で、HOSTNAME は何 byte まで設定できるか

Linux のHOSTNAMEが、何 byte まで設定できるか試してみました。

結論は、64 byte でした。



Name of the program: test-hostname
Objective: check hostname length on linux box
Author: Shintaro Fujiwara
(borrowed code snippet from

copyright Shintaro Fujiwara

Please check
man 2 gethostbyname
hint: According to below, maximum hostname is 64 bytes.

Compile: gcc -o test-hostname <file>

This program will not break anything, but execute on safe environment with your own responsibility.
This program goes with "NO WARRANTY".

You should be root to execute this program.
# ./test-hostname

---- Enjoy! ----

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

/*current hostname buffer*/
char oldname[65];
/*testhostname buffer*/
char testname[256];
/*hostname 64 bytes long*/
char name_64[256] = "123456789.123456789.123456789.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaa";
/*hostname 65 bytes long*/
char name_65[256] = "aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaaaaaa.aaaaa";

int main() {
   // save current hostname
   puts("## hostname length test program##");
   puts("## Save current hostname");
   if(!gethostname(oldname, 65))
     printf(" Saving your current hostname (%s)...\n",oldname);

  // setting hostname 64 bytes long
   puts("## Let's set host name - 64 bytes length");
   if(!sethostname(name_64, strlen(name_64)))
     printf(" Success! Set your hostname to (%s)\n", name_64);
     printf(" Oops! Failed to set your name to (%s)\n", name_64);

  // setting hostname 65 bytes long
   puts("## Let's set host name - 65 bytes length");
   if(!sethostname(name_65, strlen(name_65)))
     printf(" Success! Set your hostname to (%s)\n", name_65);
     printf(" Oops! Failed to set your name to (%s)\n", name_65);

     puts("## Let's set host name 0 byte to 70 bytes length");
     int cnt = 0;
    while (1){
     if(!sethostname(testname, cnt))
       printf("%d bytes works\n",cnt);
     printf("%d bytes does not work\n",cnt);
     if (cnt > 70)

// restore current hostname
puts("## Restore hostname");
if(!sethostname(oldname, strlen(oldname)))
   printf(" Success! Restored your hostname to (%s)\n", oldname);
   puts(" Oops! Failed to restore hostname;)");

// finish the test
puts("This will end the test.");

return 0;