[API]
sockaddr_in
socket
inet_addr
htons
WSACreateEvent
WSAEventSelect
WSACloseEvent
WSAWaitForMultipleEvents
connect
WSAGetLastError
ioctlsocket
Public CloseSocket

[INCLUDE]
Winsock

[CODE]
Public Function Winsock_Connect(ByVal Hostname As String, ByVal Port As Long, Optional ByVal TimeOut As Long = 4000&) As Long
  Dim lngHostName As Long
  Dim udtSockaddr As sockaddr_in
  Dim xLong1 As Long
  Dim hEvent As Long

  Winsock_Connect = socket(2&, 1&, 6&)   'inet / / TCP
  If Winsock_Connect > 0& Then
    lngHostName = inet_addr(Hostname)
    #If Winsock_GetHostByName Then
      If lngHostName = 0& Or lngHostName = -1& Then
        lngHostName = Winsock_GetHostByName(Hostname)
        End If
      #End If
'    If (lngHostName = 0& Or lngHostName = -1&) Then
'      lngHostName = gethostbyname(Hostname)
'      End If
    If Not (lngHostName = 0& Or lngHostName = -1&) Then
      With udtSockaddr
        .sin_family = 2& 'inet
        .sin_addr = lngHostName
        .sin_port = htons(Port)   'Remember: Network byte order
        End With
      
'Stop
      hEvent = WSACreateEvent()
      If Not hEvent = 0& Then
        'If WSAEventSelect(Winsock_Connect, hEvent, 2&) = 0& Then
        'If WSAEventSelect(Winsock_Connect, hEvent, &H10&) = 0& Then
        If WSAEventSelect(Winsock_Connect, hEvent, &H10&) = 0& Then
          Call ioctlsocket(Winsock_Connect, &H8004667E, 1&) ' good here?
          xLong1 = connect(Winsock_Connect, udtSockaddr, Len(udtSockaddr))
          If xLong1 = -1& Then
            xLong1 = WSAGetLastError()
            If xLong1 = 0 Or xLong1 = 10035& Then
              xLong1 = WSAWaitForMultipleEvents(1&, ByVal VarPtr(hEvent), 0&, TimeOut, 0&)
              'Debug.Print Hex(xLong1)
              If Not xLong1 = &H102& Then
                'Debug.Print "InTime"
                GoTo IsOK
                End If
              'Debug.Print "Timeout"
              End If
            ElseIf xLong1 = 0& Then
IsOK:
            Call WSAEventSelect(Winsock_Connect, 0&, 0&)
            Call WSACloseEvent(hEvent)
            hEvent = 0&
            'Call ioctlsocket(Winsock_Connect, &H8004667E, 0&)' just 0 stalls!
            Call ioctlsocket(Winsock_Connect, &H8004667E, 1&)
            Exit Function
            End If
          If Not hEvent = 0& Then Call WSAEventSelect(Winsock_Connect, 0&, 0&)
          End If
        If Not hEvent = 0& Then Call WSACloseEvent(hEvent)
        End If
      End If
    Call CloseSocket(Winsock_Connect)
    End If
  Winsock_Connect = 0&
  End Function