Attribute VB_Name = "WinSockLib"
Option Explicit

Public Type SocketData
    Remote          As sockaddr         ' Destination for UDPSend()s
    SockID          As Long             ' SocketID
End Type

Public MySock As SocketData     'What I send packets from

'Get an IP from a hostname
Public Function Resolve(IP As String) As String
    Dim S As String
    
    If IsNumeric(Left(IP, 1)) = True Then
        Resolve = IP
    Else
        Resolve = HostByName(IP)
    End If
End Function

'Load the overhead
Public Sub UDPStartWinsock()
    WSAStartup &H101, WSAdata
End Sub

'Unload the overhead
Public Sub UDPEndWinsock()
    WSACleanup
End Sub

'Create a SocketData structure
Public Function UDPMakeSocket(Port%, RemotePort%, IP As String) As SocketData
    Dim RetStruct As SocketData, S As Long
    S = Socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)
    sockaddr.sin_family = AF_INET
    sockaddr.sin_port = htons(Port)
    sockaddr.sin_addr = 0
    bind S, sockaddr, 16
    RetStruct.SockID = S
    RetStruct.Remote.sin_family = AF_INET
    RetStruct.Remote.sin_addr = GetHostByNameAlias(IP)
    RetStruct.Remote.sin_port = htons(RemotePort)
    UDPMakeSocket = RetStruct
End Function

'Set the packets' destination
Public Function UDPRoute(Port%, IP As String) As sockaddr
    Dim S As Long
    sockaddr.sin_addr = GetHostByNameAlias(IP)
    sockaddr.sin_family = AF_INET
    sockaddr.sin_port = htons(Port)
    UDPRoute = sockaddr
End Function

'Send the message to the given IP/Port
Public Sub UDPSend(SockData As SocketData, Message As String)
    sendto SockData.SockID, ByVal Message, Len(Message), 0, SockData.Remote, 16
End Sub
