summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--hostinfo/hostinfo.go2
-rw-r--r--hostinfo/hostinfo_test.go9
-rw-r--r--hostinfo/hostname.go13
-rw-r--r--hostinfo/hostname_macos.go30
4 files changed, 53 insertions, 1 deletions
diff --git a/hostinfo/hostinfo.go b/hostinfo/hostinfo.go
index 330669aea..298b37b66 100644
--- a/hostinfo/hostinfo.go
+++ b/hostinfo/hostinfo.go
@@ -34,7 +34,7 @@ var started = time.Now()
// New returns a partially populated Hostinfo for the current host.
func New() *tailcfg.Hostinfo {
- hostname, _ := os.Hostname()
+ hostname := GetHostname()
hostname = dnsname.FirstLabel(hostname)
return &tailcfg.Hostinfo{
IPNVersion: version.Long(),
diff --git a/hostinfo/hostinfo_test.go b/hostinfo/hostinfo_test.go
index 9fe32e044..9a2588b10 100644
--- a/hostinfo/hostinfo_test.go
+++ b/hostinfo/hostinfo_test.go
@@ -21,6 +21,15 @@ func TestNew(t *testing.T) {
t.Logf("Got: %s", j)
}
+// TestGetHostname asserts that GetHostname always returns a non-empty string.
+func TestGetHostname(t *testing.T) {
+ h := GetHostname()
+ if h == "" {
+ t.Fatalf("empty hostname")
+ }
+ t.Logf("Got: %s", h)
+}
+
func TestOSVersion(t *testing.T) {
if osVersion == nil {
t.Skip("not available for OS")
diff --git a/hostinfo/hostname.go b/hostinfo/hostname.go
new file mode 100644
index 000000000..7e1d6cdfa
--- /dev/null
+++ b/hostinfo/hostname.go
@@ -0,0 +1,13 @@
+// Copyright (c) Tailscale Inc & AUTHORS
+// SPDX-License-Identifier: BSD-3-Clause
+
+//go:build !(cgo && darwin && !ios)
+
+package hostinfo
+
+import "os"
+
+func GetHostname() string {
+ h, _ := os.Hostname()
+ return h
+}
diff --git a/hostinfo/hostname_macos.go b/hostinfo/hostname_macos.go
new file mode 100644
index 000000000..1a67f92e5
--- /dev/null
+++ b/hostinfo/hostname_macos.go
@@ -0,0 +1,30 @@
+// Copyright (c) Tailscale Inc & AUTHORS
+// SPDX-License-Identifier: BSD-3-Clause
+
+//go:build cgo && darwin && !ios
+
+package hostinfo
+
+/*
+#cgo CFLAGS: -x objective-c
+#cgo LDFLAGS: -framework Foundation
+#import <Foundation/Foundation.h>
+
+const char *getHostname() {
+ NSString *hostname = [[NSHost currentHost] localizedName];
+ if (hostname != nil) {
+ const char *hostnameCString = [hostname UTF8String];
+ if (hostnameCString != NULL) {
+ return strdup(hostnameCString);
+ }
+ }
+ return NULL;
+}
+*/
+import "C"
+
+func GetHostname() string {
+ chn := C.getHostname()
+ hostname := C.GoString(chn)
+ return hostname
+}