-
Notifications
You must be signed in to change notification settings - Fork 2
/
net.go
37 lines (33 loc) · 812 Bytes
/
net.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Copyright 2020 The GoSchedule Authors. All rights reserved.
// Use of this source code is governed by BSD
// license that can be found in the LICENSE file.
package utils
import (
"net"
"os"
"strings"
)
// GetHostIPv4 returns localhost's ip in ipv4. If failed return "127.0.0.1"
// It's suggested that the hostname is resolved to the correct address.
func GetHostIPv4() string {
hostname := GetHostName()
addrs, err := net.LookupHost(hostname)
if err != nil || len(addrs) == 0 {
return "127.0.0.1"
}
for _, ip := range addrs {
if strings.Contains(ip, ":") {
continue
}
return ip
}
return "127.0.0.1"
}
// GetHostName returns localhost's hostname. Return "localhost" for fallback
func GetHostName() string {
h, err := os.Hostname()
if err != nil {
return "localhost"
}
return h
}