如何确定给定的字符串是主机名还是 IP 地址

huangapple go评论82阅读模式
英文:

How to determine if given string is a hostname or an IP address

问题

_, err := strconv.ParseInt(host, 10, 64)
if err == nil {
hp.IpAddress = host
} else {
hp.HostName = dbhost
}

当 host = sealinuxvm11 时,我得到的错误是:

错误:strconv.ParseInt: 解析 "sealinuxvm11" 时出现无效语法

当 host = 192.168.24.10 时,

错误:strconv.ParseInt: 解析 "192.168.24.10" 时出现无效语法

英文:
_, err := strconv.ParseInt(host, 10, 64)
if err == nil {
    hp.IpAddress = host           
} else {            
    hp.HostName = dbhost 
}      

With host = sealinuxvm11 I'm getting

error strconv.ParseInt: parsing " sealinuxvm11 ": invalid syntax

and with host = 192.168.24.10

strrconv.ParseInt: parsing " 192.168.24.10": invalid syntax

答案1

得分: 15

IP地址应该被解析为字符串。我使用net包的ParseIP函数来确定给定的字符串是IP还是主机名。

addr := net.ParseIP(host)
if addr != nil {
    hp.IPAddress = host
} else {
    hp.HostName = host
}

然而,这可能会将主机名设置为无效的值。如果net.ParseIP返回错误,请检查主机名是否是有效的主机名。可以使用以下代码来确定主机名是否有效:

hostName, err := net.LookupHost(host)
if len(hostName) > 0 {
    if hostName[0] == hp.HostName {
        // 主机名有效
    }
}

正如@kostix在评论中指出的,有更好更快的方法来确定主机名是否有效。我建议你进行一些研究,了解如何实现这一点。

英文:

An IP Address should be parsed as a string. I use the net package's ParseIP to determine whether a given string is an IP or a host

addr := net.ParseIP(host)
if addr != nil {
	hp.IPAddress = host
} else {
	hp.HostName = host
}

However, this may set hostname with an invalid value. Check to make sure that host name is a valid host name if net.ParseIP returns an error. Would use

hostName, err := net.LookupHost(host)
if len(hostName) > 0{
	if hostName[0] == hp.HostName{
	}
}

to determine if the host name is valid

Like @kostix pointed out in comments there are definitely better and faster ways to determine if a host name is valid. I recommend you do some research into how that can be achieved.

huangapple
  • 本文由 发表于 2017年2月27日 14:47:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/42479410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定