Get Computer Name and logged user name

前端 未结 6 1416
走了就别回头了
走了就别回头了 2021-02-07 01:59

I am developing an application. One of the methods needs to capture the computer name and user logged on the machine, then display both to the user. I need it to run on both Win

6条回答
  •  梦毁少年i
    2021-02-07 02:29

    On POSIX systems you can use the gethostname and getlogin functions, both declared in unistd.h.

    /*
       This is a C program (I've seen the C++ tag too late).  Converting
       it to a pretty C++ program is left as an exercise to the reader.
    */
    
    #include 
    #include 
    #include 
    #include 
    
    int
    main()
    {
      char hostname[HOST_NAME_MAX];
      char username[LOGIN_NAME_MAX];
      int result;
      result = gethostname(hostname, HOST_NAME_MAX);
      if (result)
        {
          perror("gethostname");
          return EXIT_FAILURE;
        }
      result = getlogin_r(username, LOGIN_NAME_MAX);
      if (result)
        {
          perror("getlogin_r");
          return EXIT_FAILURE;
        }
      result = printf("Hello %s, you are logged in to %s.\n",
                      username, hostname);
      if (result < 0)
        {
          perror("printf");
          return EXIT_FAILURE;
        }
      return EXIT_SUCCESS;
    }
    

    Possible output:

    Hello 5gon12eder, you are logged in to example.com.
    

    This seems safer than relying on environment variables which are not always present.

    I'm withdrawing that last statement because

    • the man page of getlogin actually discourages its usage in favour of getenv("LOGIN") and
    • the getlogin_r call in the above program fails with ENOTTY when I run the program from within Emacs instead of an interactive terminal while getenv("USER") would have worked in both situations.

提交回复
热议问题