Visual Basic 6 function "IsValidHostname"

Go back

Below you'll find the source for the Visual Basic 6 function IsValidHostname.

Attribute VB_Name = "modIsValidHostname"
' This function is downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Option Explicit

''
' Checks if a hostname is valid
' @param    String  hostname   The hostname that needs checking
' @return   Boolean            True if it's valid, false if it's not
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function IsValidHostname(ByVal hostname As String) As Boolean
    ' A hostname may not be longer then 255 characters
    If Len(hostname) > 255 Then Exit Function
    
    ' A hostname is built up of multiple parts;
    ' - with a minimum length of 1 character
    ' - with a maximum length of 63 characters
    ' - which may not start nor end with a hyphen
    Dim parts() As String, i As Integer
    parts = Split(hostname, ".")
    For i = LBound(parts) To UBound(parts)
        If Len(parts(i)) < 1 Or Len(parts(i)) > 63 Then Exit Function
        If Left(parts(i), 1) = "-" Then Exit Function
        If Right(parts(i), 1) = "-" Then Exit Function
    Next i
    
    ' Lets make the value lower case, makes compairing easier
    hostname = LCase(hostname)
    
    ' A hostname may only contain dots, hyphens, letters (a-z) and digits (0-9)
    Dim charcode As Integer
    For i = 1 To Len(hostname)
        charcode = Asc(Mid(hostname, i, 1))
        ' 45=- 46=. 48=0 57=9 97=a 122=z
        If (charcode < 97 Or charcode > 122) And _
           (charcode < 48 Or charcode > 57) And _
           charcode <> 45 And charcode <> 46 Then Exit Function
    Next i
    
    IsValidHostname = True
End Function