Blame view

tests/udptst.cpp 1.41 KB
48b4c725   Peter M. Groen   Setting up Socket-pp
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
  // udptst.cpp
  
  #include <iostream>
  #include "sockpp/socket.h"
  
  using namespace std;
  
  // --------------------------------------------------------------------------
  
  int do_recv(sockpp::udp_socket& sock)
  {
  	char buf[6];
  	int n = sock.recv(buf, sizeof(buf));
  
  	if (n < 0) {
  		cerr << "Error sending packet: ["
  			<< sock.last_error() << "]" << endl;
  		return -1;
  	}
  
  	cout << "Received " << n << " bytes" << flush;
  	buf[n] = '\0';
  	cout << " '" << buf << "'" << endl;
  	return 0;
  }
  
  // --------------------------------------------------------------------------
  
  int main()
  {
  	in_port_t port = 12345;
  
  	cout << "Testing UDP sockets" << endl;
  	sockpp::udp_socket srvrSock;
  
  	if (!srvrSock) {
  		cerr << "Error creating server socket [" 
  			<< srvrSock.last_error() << "]" << endl;
  		return 1;
  	}
  
  	if (!srvrSock.bind(port)) {
  		cerr << "Error binding to port: " << port << " [" 
  			<< srvrSock.last_error() << "]" << endl;
  		return 1;
  	}
  
  	sockpp::udp_socket cliSock;
  
  	if (!cliSock) {
  		cerr << "Error creating server socket [" 
  			<< cliSock.last_error() << "]" << endl;
  		return 1;
  	}
  
  	sockpp::inet_address localAddr("localhost", port);
  
  	if (!cliSock.connect(localAddr)) {
  		cerr << "Error connecting to port: " << port << " [" 
  			<< cliSock.last_error() << "]" << endl;
  		return 1;
  	}
  
  	cliSock.send("Hello");
  	do_recv(srvrSock);
  
  	cliSock.close();
  
  	sockpp::udp_socket sock;
  	sock.sendto("bubba", localAddr);
  	do_recv(srvrSock);
  
  	return 0;
  }