Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 1 | // 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 Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 4 | |
| 5 | #include "wpi/hostname.h" |
| 6 | |
| 7 | #include <cstdlib> |
| 8 | #include <string> |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 9 | #include <string_view> |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 10 | |
| 11 | #include "uv.h" |
| 12 | #include "wpi/SmallVector.h" |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 13 | |
| 14 | namespace wpi { |
| 15 | |
| 16 | std::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 Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 27 | if (err == 0) { |
| 28 | rv.assign(name2, size); |
| 29 | } |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 30 | std::free(name2); |
| 31 | } |
| 32 | |
| 33 | return rv; |
| 34 | } |
| 35 | |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 36 | std::string_view GetHostname(SmallVectorImpl<char>& name) { |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 37 | // 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 Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 49 | if (err != 0) { |
| 50 | size = 0; |
| 51 | } |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 52 | } |
| 53 | |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 54 | return {name.data(), size}; |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 55 | } |
| 56 | |
| 57 | } // namespace wpi |