mirror of
https://github.com/wpilibsuite/allwpilib
synced 2026-06-20 00:51:42 +00:00
[wpinet] Move network portions of wpiutil into new wpinet library (#4077)
This commit is contained in:
58
wpinet/src/main/native/cpp/hostname.cpp
Normal file
58
wpinet/src/main/native/cpp/hostname.cpp
Normal file
@@ -0,0 +1,58 @@
|
||||
// Copyright (c) FIRST and other WPILib contributors.
|
||||
// Open Source Software; you can modify and/or share it under the terms of
|
||||
// the WPILib BSD license file in the root directory of this project.
|
||||
|
||||
#include "wpinet/hostname.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include <wpi/SmallVector.h>
|
||||
|
||||
#include "uv.h"
|
||||
|
||||
namespace wpi {
|
||||
|
||||
std::string GetHostname() {
|
||||
std::string rv;
|
||||
char name[256];
|
||||
size_t size = sizeof(name);
|
||||
|
||||
int err = uv_os_gethostname(name, &size);
|
||||
if (err == 0) {
|
||||
rv.assign(name, size);
|
||||
} else if (err == UV_ENOBUFS) {
|
||||
char* name2 = static_cast<char*>(std::malloc(size));
|
||||
err = uv_os_gethostname(name2, &size);
|
||||
if (err == 0) {
|
||||
rv.assign(name2, size);
|
||||
}
|
||||
std::free(name2);
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
std::string_view GetHostname(SmallVectorImpl<char>& name) {
|
||||
// Use a tmp array to not require the SmallVector to be too large.
|
||||
char tmpName[256];
|
||||
size_t size = sizeof(tmpName);
|
||||
|
||||
name.clear();
|
||||
|
||||
int err = uv_os_gethostname(tmpName, &size);
|
||||
if (err == 0) {
|
||||
name.append(tmpName, tmpName + size);
|
||||
} else if (err == UV_ENOBUFS) {
|
||||
name.resize(size);
|
||||
err = uv_os_gethostname(name.data(), &size);
|
||||
if (err != 0) {
|
||||
size = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return {name.data(), size};
|
||||
}
|
||||
|
||||
} // namespace wpi
|
||||
Reference in New Issue
Block a user