blob: d907023ff4cf7dec293c9886ab59ec5eb1a0ad12 [file] [log] [blame]
Austin Schuh812d0d12021-11-04 20:16:48 -07001// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
Brian Silverman8fce7482020-01-05 13:18:21 -08004
5#include "wpi/hostname.h"
6
7#include <cstdlib>
8#include <string>
Austin Schuh812d0d12021-11-04 20:16:48 -07009#include <string_view>
Brian Silverman8fce7482020-01-05 13:18:21 -080010
11#include "uv.h"
12#include "wpi/SmallVector.h"
Brian Silverman8fce7482020-01-05 13:18:21 -080013
14namespace wpi {
15
16std::string GetHostname() {
17 std::string rv;
18 char name[256];
19 size_t size = sizeof(name);
20
21 int err = uv_os_gethostname(name, &size);
22 if (err == 0) {
23 rv.assign(name, size);
24 } else if (err == UV_ENOBUFS) {
25 char* name2 = static_cast<char*>(std::malloc(size));
26 err = uv_os_gethostname(name2, &size);
Austin Schuh812d0d12021-11-04 20:16:48 -070027 if (err == 0) {
28 rv.assign(name2, size);
29 }
Brian Silverman8fce7482020-01-05 13:18:21 -080030 std::free(name2);
31 }
32
33 return rv;
34}
35
Austin Schuh812d0d12021-11-04 20:16:48 -070036std::string_view GetHostname(SmallVectorImpl<char>& name) {
Brian Silverman8fce7482020-01-05 13:18:21 -080037 // Use a tmp array to not require the SmallVector to be too large.
38 char tmpName[256];
39 size_t size = sizeof(tmpName);
40
41 name.clear();
42
43 int err = uv_os_gethostname(tmpName, &size);
44 if (err == 0) {
45 name.append(tmpName, tmpName + size);
46 } else if (err == UV_ENOBUFS) {
47 name.resize(size);
48 err = uv_os_gethostname(name.data(), &size);
Austin Schuh812d0d12021-11-04 20:16:48 -070049 if (err != 0) {
50 size = 0;
51 }
Brian Silverman8fce7482020-01-05 13:18:21 -080052 }
53
Austin Schuh812d0d12021-11-04 20:16:48 -070054 return {name.data(), size};
Brian Silverman8fce7482020-01-05 13:18:21 -080055}
56
57} // namespace wpi