c - 无法将 char 指针传递给 gethostname (Linux)

标签 c hostname rhel unistd.h

以下 C 程序尝试获取并打印当前 RHEL 主机的主机名。它在这台机器上抛出一个段错误。根据 gethostname 的定义我应该能够传递一个 char 指针,不是吗?

当我改用 char 数组时(如 char hname[255]),对 gethostname 的调用有效。 (如果我这样做,我将如何将数组返回到 main?)

#include <stdio.h>
#include <unistd.h>
char * fetchHostname()
{

    // using "char hname[255]" gets me around the issue;
    // however, I dont understand why I'm unable to use
    // a char pointer.

    char *hname;
    gethostname(hname, 255 );

    return hname;

}

int main()
{
    char *hostname = fetchHostname();
    return 0;
}

输出:

pmn@rhel /tmp/temp > gcc -g test.c -o test
pmn@rhel /tmp/temp >

pmn@rhel /tmp/temp > ./test
Segmentation fault
pmn@rhel /tmp/temp >

最佳答案

正如 gethostname 人所说:

The gethostname() function shall return the standard host name for the current machine. The namelen argument shall specify the size of the array pointed to by the name argument. The returned name shall be null-terminated, except that if namelen is an insufficient length to hold the host name, then the returned name shall be truncated and it is unspecified whether the returned name is null-terminated.

您需要一个地方来存储函数信息,因此将主机名声明为数组,而不是指针。

#include <unistd.h>

char * fetchHostname(char *hostname, int size)
{

    // using "char hname[255]" gets me around the issue;
    // however, I dont understand why I'm unable to use
    // a char pointer.
    gethostname(hostname, size);

    return hostname;
}

int main()
{
    char hostname[HOST_NAME_MAX + 1];

    fetchHostname(hostname, HOST_NAME_MAX);
    return 0;
}

关于c - 无法将 char 指针传递给 gethostname (Linux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20796823/

相关文章:

java - 为什么方法不能返回多个值

linux - 在 RHEL 的特定文件夹中安装 Jenkins

mysql - 为什么 MySQL 内置函数 'current_user()' 返回包含 '%' 符号的主机名?

linux - 如何在 Linux 中将一组软件作为一个软件包安装?

linux - ntpdate 总是与一些偏移量进行同步

c - 求冒泡排序的时间复杂度?

c - C 结构体数组中的 qsort()

java - 我的项目中有 NaN 错误已编辑

amazon-web-services - Amazon EC2 主机名

c# - 不修改hosts文件的主机名解析