summaryrefslogtreecommitdiff
path: root/src/tests/udpsocket.cpp
blob: 18c7bb982fb41e9abd4c3662b761413bc6f9f1b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "bu/udpsocket.h"
#include "bu/sio.h"

#include <errno.h>
#include <arpa/inet.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/utsname.h>

using namespace Bu;

int main( int argc, char *argv[] )
{
	sio << Fmt::hex(8) << INADDR_ANY << sio.nl << Fmt::hex(8) << inet_addr("0.0.0.0") << sio.nl;
	if( argc == 1 )
	{
		sio << "Options are 'l' for listening and 'b' for broadcasting."
			<< sio.nl;
	}
	else if( argv[1][0] == 'l' )
	{
		sio << "Listening..." << sio.nl;
		Bu::UdpSocket udp( "0.0.0.0", 6688, UdpSocket::Read|UdpSocket::Broadcast );

		for(;;)
		{
			char buf[1501];
			int iRead = udp.read( buf, 1500 );
			if( iRead >= 0 )
			{
				buf[iRead] = '\0';
				sio << "Read(" << iRead << "): '" << buf << "'" << sio.nl;
			}
			else
			{
				sio << "Got " << iRead << ": " << strerror( errno ) << sio.nl;
			}
		}
	}
	else if( argv[1][0] == 'L' )
	{
		sio << "Listening..." << sio.nl;
		Bu::UdpSocket udp( "0.0.0.0", 6688, UdpSocket::Read|UdpSocket::Broadcast );

		for(;;)
		{
			char buf[1501];
			Bu::UdpSocket::addr aHost;
			int iPort;
			int iRead = udp.read( buf, 1500, aHost, iPort );
			if( iRead >= 0 )
			{
				buf[iRead] = '\0';
				sio << "Read(" << iRead << ") from " << Bu::UdpSocket::addrToStr( aHost ) << ":" << iPort << ": '" << buf << "'" << sio.nl;
			}
		}
	}
	else if( argv[1][0] == 'b' )
	{
		sio << "Broadcasting..." << sio.nl;
		Bu::UdpSocket udp("255.255.255.255", 6688,
				UdpSocket::Write|UdpSocket::Broadcast );

		for(;;)
		{
			int iWrote = udp.write("hello", 5 );
			sio << "Wrote(" << iWrote << "): " << strerror( errno ) << sio.nl;
			usleep( 250000 );
		}
	}
	else
	{
		sio << "Options are 'l' for listening and 'b' for broadcasting."
			<< sio.nl;
	}

	return 0;
}