Attribute VB_Name = "modWinsock"
'-----------------------------------------------------
' MirageBot Winsock Manipulation Module
' Written by Christopher Nevin (lancergli@gmail.com)
'-----------------------------------------------------

Option Explicit

Private Declare Function gethostbyname Lib "wsock32" (ByVal hostname As String) As Long
Private Declare Function gethostbyaddr Lib "wsock32.dll" (haddr As Long, ByVal hnlen As Long, ByVal addrtype As Long) As Long
Private Declare Function lstrlenA Lib "kernel32" (lpString As Any) As Long
Private Declare Function WSAStartup Lib "wsock32.dll" (ByVal wVersionRequired As Long, lpWSADATA As WSADATA) As Long
Private Declare Function WSACleanup Lib "wsock32.dll" () As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare Function IcmpCreateFile Lib "icmp.dll" () As Long
Private Declare Function IcmpCloseHandle Lib "icmp.dll" (ByVal IcmpHandle As Long) As Long
Private Declare Function IcmpSendEcho Lib "icmp.dll" (ByVal IcmpHandle As Long, ByVal DestinationAddress As Long, ByVal RequestData As String, ByVal RequestSize As Long, ByVal RequestOptions As Long, ReplyBuffer As ICMP_ECHO_REPLY, ByVal ReplySize As Long, ByVal Timeout As Long) As Long
Private Declare Function lstrcpyA Lib "kernel32" (ByVal RetVal As String, ByVal Ptr As Long) As Long

Public Declare Function inet_addr Lib "wsock32" (ByVal S As String) As Long
Public Declare Function inet_ntoa Lib "wsock32.dll" (ByVal addr As Long) As Long
Public Declare Function setsockopt Lib "ws2_32.dll" (ByVal S As Long, ByVal Level As Long, ByVal optname As Long, optval As Any, ByVal optlen As Long) As Long 'Set socket options
Public Declare Function htons Lib "ws2_32" (ByVal hostshort As Long) As Integer
Public Declare Function ntohs Lib "ws2_32" (ByVal netshort As Long) As Integer

Private Const TNODELAY As Long = 1 '(BOOL) Nagel Algorithm
Private Const IPPROTO_TCP As Long = 6
Private Const IP_SUCCESS As Long = 0
Private Const IP_STATUS_BASE As Long = 11000
Private Const IP_BUF_TOO_SMALL As Long = (IP_STATUS_BASE + 1)
Private Const IP_DEST_NET_UNREACHABLE As Long = (IP_STATUS_BASE + 2)
Private Const IP_DEST_HOST_UNREACHABLE As Long = (IP_STATUS_BASE + 3)
Private Const IP_DEST_PROT_UNREACHABLE As Long = (IP_STATUS_BASE + 4)
Private Const IP_DEST_PORT_UNREACHABLE As Long = (IP_STATUS_BASE + 5)
Private Const IP_NO_RESOURCES As Long = (IP_STATUS_BASE + 6)
Private Const IP_BAD_OPTION As Long = (IP_STATUS_BASE + 7)
Private Const IP_HW_ERROR As Long = (IP_STATUS_BASE + 8)
Private Const IP_PACKET_TOO_BIG As Long = (IP_STATUS_BASE + 9)
Private Const IP_REQ_TIMED_OUT As Long = (IP_STATUS_BASE + 10)
Private Const IP_BAD_REQ As Long = (IP_STATUS_BASE + 11)
Private Const IP_BAD_ROUTE As Long = (IP_STATUS_BASE + 12)
Private Const IP_TTL_EXPIRED_TRANSIT As Long = (IP_STATUS_BASE + 13)
Private Const IP_TTL_EXPIRED_REASSEM As Long = (IP_STATUS_BASE + 14)
Private Const IP_PARAM_PROBLEM As Long = (IP_STATUS_BASE + 15)
Private Const IP_SOURCE_QUENCH As Long = (IP_STATUS_BASE + 16)
Private Const IP_OPTION_TOO_BIG As Long = (IP_STATUS_BASE + 17)
Private Const IP_BAD_DESTINATION As Long = (IP_STATUS_BASE + 18)
Private Const IP_ADDR_DELETED As Long = (IP_STATUS_BASE + 19)
Private Const IP_SPEC_MTU_CHANGE As Long = (IP_STATUS_BASE + 20)
Private Const IP_MTU_CHANGE As Long = (IP_STATUS_BASE + 21)
Private Const IP_UNLOAD As Long = (IP_STATUS_BASE + 22)
Private Const IP_ADDR_ADDED As Long = (IP_STATUS_BASE + 23)
Private Const IP_GENERAL_FAILURE As Long = (IP_STATUS_BASE + 50)
Private Const IP_PENDING As Long = (IP_STATUS_BASE + 255)
Private Const MAX_IP_STATUS As Long = (IP_STATUS_BASE + 50)
Private Const PING_TIMEOUT As Long = 1000
Private Const INADDR_NONE As Long = &HFFFFFFFF
Private Const SOCKET_ERROR As Long = -1
Private Const MAX_WSADescription As Long = 256
Private Const MAX_WSASYSStatus As Long = 128
Private Const MIN_SOCKETS_REQD As Long = 1
Private Const WS_VERSION_REQD As Long = &H101
Private Const WS_VERSION_MAJOR As Long = WS_VERSION_REQD \ &H100 And &HFF&
Private Const WS_VERSION_MINOR As Long = WS_VERSION_REQD And &HFF&
Private Const WSADescription_Len As Long = 256
Private Const WSASYS_Status_Len As Long = 128
Private Const AF_INET As Long = 2

Private Type HOSTENT
    hName As Long
    hTags As Long
    hAddrType As Integer
    hLength As Integer
    hAddrList As Long
End Type
 
Private Type WSADATA
   wVersion As Integer
   wHighVersion As Integer
   szDescription(0 To MAX_WSADescription) As Byte
   szSystemStatus(0 To MAX_WSASYSStatus) As Byte
   wMaxSockets As Long
   wMaxUDPDG As Long
   dwVendorInfo As Long
End Type

Private Type ICMP_OPTIONS
   Ttl             As Byte
   Tos             As Byte
   Flags           As Byte
   OptionsSize     As Byte
   OptionsData     As Long
End Type

Private Type ICMP_ECHO_REPLY
   Address         As Long
   Status          As Long
   RoundTripTime   As Long
   DataSize        As Long
  'Reserved        As Integer
   DataPointer     As Long
   Options         As ICMP_OPTIONS
   Data            As String * 250
End Type

Public Function GetIPFromHostName(ByVal sHostName As String) As String
    Dim ptrHosent As Long
    Dim ptrAddress As Long
    Dim ptrIPAddress As Long
    Dim sAddress As String
    
    sAddress = Space$(4)

    DoEvents
    ptrHosent = gethostbyname(sHostName & vbNullChar)
    
    If ptrHosent <> 0 Then
       ptrAddress = ptrHosent + 12
     
       CopyMemory ptrAddress, ByVal ptrAddress, 4
       CopyMemory ptrIPAddress, ByVal ptrAddress, 4
       CopyMemory ByVal sAddress, ByVal ptrIPAddress, 4
    
       GetIPFromHostName = IPToText(sAddress)
    End If
End Function

Private Function IPToText(ByVal IPAddress As String) As String
   IPToText = CStr(Asc(IPAddress)) & "." & _
              CStr(Asc(Mid$(IPAddress, 2, 1))) & "." & _
              CStr(Asc(Mid$(IPAddress, 3, 1))) & "." & _
              CStr(Asc(Mid$(IPAddress, 4, 1)))
End Function

Private Function InitializeSocket() As Boolean
    Dim WSAD As WSADATA
    InitializeSocket = WSAStartup(WS_VERSION_REQD, WSAD) = IP_SUCCESS
End Function

Public Sub CloseSocket()
    If WSACleanup() <> 0 Then
        'MsgBox "Error calling apiWSACleanup.", vbCritical
    End If
End Sub

Public Function ToggleNagel(ByVal SocketHandle As Long, Disabled As Boolean) As Boolean
    'Error setting TNODELAY
    ToggleNagel = Not (setsockopt(SocketHandle, IPPROTO_TCP, TNODELAY, CLng(Disabled), 4) = SOCKET_ERROR)
    'The Nagel Algorithim is now disabled allowing for a speedy connection
    End Function

Public Function GetHostNameFromIP(ByVal sIPAddress As String) As String
    Dim ptrHosent As Long
    Dim hAddress As Long
    Dim sHost As String
    Dim nbytes As Long
    
    'try to open the socket
    If InitializeSocket() = True Then
        'convert string address to long datatype
        hAddress = inet_addr(sIPAddress)
       
        'check if an error ocucred
        If hAddress <> SOCKET_ERROR Then
            'obtain a pointer to the HOSTENT structure
            'that contains the name and address
            'corresponding to the given network address.
            ptrHosent = gethostbyaddr(hAddress, 4, AF_INET)
           
            If ptrHosent <> 0 Then
                'convert address and
                'get resolved hostname
                CopyMemory ptrHosent, ByVal ptrHosent, 4
                nbytes = lstrlenA(ByVal ptrHosent)
               
                If nbytes > 0 Then
                    'fill the IP address buffer
                    sHost = Space$(nbytes)
                   
                    CopyMemory ByVal sHost, ByVal ptrHosent, nbytes
                    GetHostNameFromIP = sHost
                End If
            Else
                GetHostNameFromIP = sIPAddress
                'MsgBox "Call to gethostbyaddr failed."
            End If
            'close the socket
            CloseSocket
        Else
            GetHostNameFromIP = sIPAddress
            'MsgBox "Invalid IP address"
        End If
    Else
        GetHostNameFromIP = sIPAddress
        'MsgBox "Failed to open Socket"
    End If
End Function

Private Function Ping(sAddress As String, _
                      sDataToSend As String, _
                      ECHO As ICMP_ECHO_REPLY) As Long

  'If Ping succeeds :
  '.RoundTripTime = time in ms for the ping to complete,
  '.Data is the data returned (NULL terminated)
  '.Address is the IP address that actually replied
  '.DataSize is the size of the string in .Data
  '.Status will be 0
  '
  'If Ping fails .Status will be the error code
   
   Dim hPort As Long
   Dim dwAddress As Long
   
  'convert the address into a long representation
   dwAddress = inet_addr(sAddress)
   
  'if dwAddress is valid
   If dwAddress <> INADDR_NONE Then
   
     'open a port
      hPort = IcmpCreateFile()
      
     'and if successful,
      If hPort Then
      
        'ping it.
         Call IcmpSendEcho(hPort, _
                           dwAddress, _
                           sDataToSend, _
                           Len(sDataToSend), _
                           0, _
                           ECHO, _
                           Len(ECHO), _
                           PING_TIMEOUT)

        'return the status as ping success
         Ping = ECHO.Status

        'close the port handle
         Call IcmpCloseHandle(hPort)
      
      End If  'If hPort
      
   Else
   
        'the address format was probably invalid
         Ping = INADDR_NONE
   End If
End Function

Private Function GetStrFromPtrA(ByVal lpszA As Long) As String
   GetStrFromPtrA = String$(lstrlenA(ByVal lpszA), 0)
   Call lstrcpyA(ByVal GetStrFromPtrA, ByVal lpszA)
End Function

Public Sub SocketsCleanup()
   If WSACleanup() <> 0 Then MsgBox "Windows Sockets error occurred in Cleanup.", vbExclamation
End Sub

Private Function SocketsInitialize() As Boolean
   Dim WSAD As WSADATA
   SocketsInitialize = WSAStartup(WS_VERSION_REQD, WSAD) = IP_SUCCESS
End Function

Public Function PingServer(Server As String) As Long
    If SocketsInitialize() Then
        Dim ECHO As ICMP_ECHO_REPLY
        Dim Success As Long
        Dim sIPAddress As String
        sIPAddress = GetIPFromHostName(Server)
        Success = Ping(sIPAddress, "Echo this", ECHO)
        If Success = IP_SUCCESS Then
            PingServer = ECHO.RoundTripTime
        Else
            PingServer = -1
        End If
        SocketsCleanup
    Else
        PingServer = -1
    End If
End Function
