天天看點

gethostname()、sethostname()和getdomainname()、setdomainname()函數

(1)gethostname()、sethostname()函數,擷取/設定本地主機的标準主機名

int main (int argc, char *argv[])
{
    char buf[50];

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

    return 0;
}      

程式輸出:

[[email protected] ~]# ./a.out

localhost.localdomain

[[email protected] ~]#

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

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

    return 0;
}      

程式輸出:

[[email protected] ~]# ./a.out

sethostname success!

[[email protected] ~]#

(2)getdomainname()、setdomainname()函數,擷取/設定本地主機的域名

int main (int argc, char *argv[])
{
    char buf[50];

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

程式輸出:

[[email protected] ~]# ./a.out

www.robot.com

[[email protected] ~]#

int main (int argc, char *argv[])
{
    char buf[50] = "www.robot.com";

    if (setdomainname(buf, sizeof("www.robot.com")) < 0)
    {   
        perror("setdomainname");
    }   
    else
    {   
        printf("setdomainname success!\n");
    }   
    
    return 0;
}      

程式輸出:

[[email protected] ~]# ./a.out

setdomainname success!

[[email protected] ~]#

轉載于:https://www.cnblogs.com/Robotke1/archive/2013/05/08/3067096.html