Golang : Check if IP address is version 4 or 6
Problem :
Your Golang program needs to determine if a given IP address is version 4 or 6.
Solution :
Not really a fool proof solution, but it should be sufficient to detect if a given string has a decimal or colon in it. If the string has decimal as separator, then it is IP version 4 and if colon, then it is IP version 6.
Here you go :
package main
import (
"fmt"
"net"
)
func ip4or6(s string) string {
for i := 0; i < len(s); i++ {
switch s[i] {
case '.':
return "version 4"
case ':':
return "version 6"
}
}
return "unknown"
}
func main() {
var ipAddress string = "192.168.0.1"
//sanity check
testInput := net.ParseIP(ipAddress)
if testInput.To4() == nil {
fmt.Printf("%v is not a valid IPv4 address\n", testInput)
}
fmt.Printf("%s is IP address of : %s \n", ipAddress, ip4or6(ipAddress))
var ip6Address string = "FE80::0202:B3FF:FE1E:8329"
//sanity check
testInputIP6 := net.ParseIP(ip6Address)
if testInputIP6.To16() == nil {
fmt.Printf("%v is not a valid IP address\n", testInputIP6)
}
fmt.Printf("%s is IP address of : %s \n", ip6Address, ip4or6(ip6Address))
var ip6AddressURLPort string = "http://[2001:db8:0:1]:80"
//sanity check
testInputIP6URLPort := net.ParseIP(ip6AddressURLPort)
if testInputIP6URLPort.To16() == nil {
fmt.Printf("%v is not a valid IP address\n", ip6AddressURLPort)
}
fmt.Printf("%s is IP address of : %s \n", ip6AddressURLPort, ip4or6(ip6AddressURLPort))
}
Output :
192.168.0.1 is IP address of : version 4
FE80::0202:B3FF:FE1E:8329 is IP address of : version 6
http://[2001:db8:0:1]:80 is not a valid IP address
http://[2001:db8:0:1]:80 is IP address of : version 6
References :
See also : Golang : How to check if IP address is in range
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+31.2k Golang : bufio.NewReader.ReadLine to read file line by line
+7k Nginx : How to block user agent ?
+26.2k Golang : Get executable name behind process ID example
+17.6k Golang : Iterate linked list example
+6.8k Golang : Decode XML data from RSS feed
+15.1k Golang : Get all local users and print out their home directory, description and group id
+11.2k Golang : How to flush a channel before the end of program?
+12k Golang : Get remaining text such as id or filename after last segment in URL path
+9.1k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+13.6k Golang : Tutorial on loading GOB and PEM files
+7.7k Golang : Load DSA public key from file example
+5.8k Golang : Denco multiplexer example