英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论