Files
allwpilib/wpiutil/src/main/native/cpp/hostname.cpp

57 lines
1.5 KiB
C++
Raw Normal View History

2017-08-27 21:35:34 -07:00
/*----------------------------------------------------------------------------*/
2018-01-01 17:32:39 -08:00
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
2017-08-27 21:35:34 -07:00
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "wpi/hostname.h"
2017-08-27 21:35:34 -07:00
#include <cstdlib>
2017-08-27 21:35:34 -07:00
#include <string>
2017-10-21 20:31:20 -07:00
#include "uv.h"
#include "wpi/SmallVector.h"
#include "wpi/StringRef.h"
2017-08-27 21:35:34 -07:00
namespace wpi {
std::string GetHostname() {
std::string rv;
2017-08-27 21:35:34 -07:00
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;
2017-08-27 21:35:34 -07:00
}
StringRef GetHostname(SmallVectorImpl<char>& name) {
2017-08-27 21:35:34 -07:00
// Use a tmp array to not require the SmallVector to be too large.
char tmpName[256];
size_t size = sizeof(tmpName);
2017-08-27 21:35:34 -07:00
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 StringRef{name.data(), size};
2017-08-27 21:35:34 -07:00
}
2017-08-27 21:35:34 -07:00
} // namespace wpi