1 /* Echo server (UDP)
2  * Copyright (C) 2000  David Helder
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13 
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor,
17  * Boston, MA  02110-1301  USA
18  */
19 
20 
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <glib.h>
25 #include <gnet.h>
26 
27 
28 
29 int
main(int argc,char ** argv)30 main(int argc, char** argv)
31 {
32   int port = 0;
33   GUdpSocket* server;
34   gchar buffer[1024];
35   gint ttl;
36   gint rv;
37   GInetAddr* addr;
38   gchar* name;
39 
40   gnet_init ();
41 
42   if (argc !=  2)
43     {
44       g_print ("usage: echoserver-udp <port> \n");
45       exit(EXIT_FAILURE);
46     }
47   port = atoi(argv[argc - 1]);
48 
49   /* Create the server */
50   server = gnet_udp_socket_new_with_port (port);
51   g_assert (server);
52 
53   /* Get the TTL (for fun) */
54   ttl = gnet_udp_socket_get_ttl (server);
55   g_assert (ttl >= -1);
56 
57   /* Set the TTL to 64 (the default on many systems) */
58   rv = gnet_udp_socket_set_ttl (server, 64);
59   g_assert (rv == 0);
60 
61   ttl = gnet_udp_socket_get_ttl (server);
62   g_assert (ttl == 64);
63 
64   /* Print the address */
65   addr = gnet_udp_socket_get_local_inetaddr(server);
66   g_assert (addr);
67   name = gnet_inetaddr_get_canonical_name (addr);
68   g_assert (name);
69   port = gnet_inetaddr_get_port (addr);
70   g_print ("UDP echoserver running on %s:%d\n", name, port);
71   gnet_inetaddr_delete (addr);
72   g_free (name);
73 
74   while (1)
75     {
76       gint bytes_received;
77       gint rv;
78 
79       bytes_received = gnet_udp_socket_receive (server, buffer, sizeof(buffer),
80 						&addr);
81       if (bytes_received == -1)
82 	continue;
83 
84       rv = gnet_udp_socket_send (server, buffer, bytes_received, addr);
85       g_assert (rv == 0);
86 
87       gnet_inetaddr_delete (addr);
88     }
89 
90   return 0;
91 
92 }
93 
94 
95