LB Booster
Programming >> BASIC code examples >> Sending UDP data packets
http://lbb.conforums.com/index.cgi?board=code&action=display&num=1451484432

Sending UDP data packets
Post by Richard Russell on Dec 30th, 2015, 1:07pm

There is an ongoing discussion at the Liberty BASIC Yahoo! Group about sending UDP (User Datagram Protocol) packets from an LB program. This is a straightforward thing to do in LB or LBB code (sending UDP packets is probably the simplest of all socket transactions) yet, strangely, the majority of replies there have implied that it is difficult or impossible to achieve without an external 'helper' application!

I have listed below a program to demonstrate just how easy it is to send UDP packets from LB/LBB. For convenience the program goes through the entire startup, open socket, send packet, close socket, shutdown sequence for every packet sent. This should be OK so long as packets are being sent relatively infrequently, but in a program that sends large numbers of packets in quick succession it would be better to keep the socket open for the duration.

Of course I cannot reply to the LB Group myself, which is why I am posting the information here.

Richard.

Code:
    open "WS2_32" for DLL as #winsock
    
    packet$ = "Hello world!"
    ok = UDPsend("127.0.0.1", 12080, packet$)
    if ok then print "Packet sent" else print "UDPsend failed"
    
    close #winsock
    end
    
function UDPsend(addr$, port, msg$)
    AF.INET = 2
    SOCK.DGRAM = 2
    IPPROTO.UDP = 17
    UDPsend = 0
    
    port = (port and hexdec("FF00")) / 256 + (port and 255) * 256 ' swap bytes
    calldll #winsock, "inet_addr", addr$ as ptr, ipaddr as ulong
        
    struct WSAdata, d as char[398]
    calldll #winsock, "WSAStartup", 514 as long, WSAdata as struct, ret as long
    if ret then exit function
    
    calldll #winsock, "socket", AF.INET as long, SOCK.DGRAM as long, _
                      IPPROTO.UDP as long, socket as long
    if socket = -1 then exit function
    
    struct addr, family as short, port as short, addr as ulong, zero as char[8]
    addr.family.struct = AF.INET
    addr.port.struct = port
    addr.addr.struct = ipaddr

    al = len(addr.struct)
    ml = len(msg$)
    calldll #winsock, "sendto", socket as long, msg$ as ptr, ml as long, _
                      0 as long, addr as struct, al as long, sent as long

    calldll #winsock, "closesocket", socket as long, ret as long
    calldll #winsock, "WSACleanup", ret as long
    
    if sent = ml then UDPsend = 1
end function