Merge from build
[m6w6/libmemcached] / libtest / port.cc
1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
2 *
3 * libtest
4 *
5 * Copyright (C) 2011 Data Differential, http://datadifferential.com/
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 3 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include <libtest/common.h>
23
24 #include <cassert>
25 #include <cstdlib>
26 #include <cstring>
27 #include <ctime>
28 #include <fnmatch.h>
29 #include <iostream>
30 #include <sys/socket.h>
31 #include <sys/stat.h>
32 #include <sys/time.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <unistd.h>
36
37 #include <signal.h>
38
39 #include <libtest/stats.h>
40 #include <libtest/signal.h>
41
42 #ifndef __INTEL_COMPILER
43 #pragma GCC diagnostic ignored "-Wold-style-cast"
44 #endif
45
46 using namespace libtest;
47
48 static in_port_t global_port= 0;
49 static in_port_t global_max_port= 0;
50
51 namespace libtest {
52
53 in_port_t default_port()
54 {
55 return global_port;
56 }
57
58 void set_default_port(in_port_t port)
59 {
60 global_port= port;
61 }
62
63 in_port_t max_port()
64 {
65 return global_max_port;
66 }
67
68 void set_max_port(in_port_t port)
69 {
70 if (port > global_max_port)
71 {
72 global_max_port= port;
73 }
74
75 global_max_port= port;
76 }
77
78 in_port_t get_free_port()
79 {
80 in_port_t ret_port= in_port_t(0);
81 int sd;
82 if ((sd= socket(AF_INET, SOCK_STREAM, 0)) != -1)
83 {
84 int optval= 1;
85 if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) != -1)
86 {
87 struct sockaddr_in sin;
88 sin.sin_port= 0;
89 sin.sin_addr.s_addr= 0;
90 sin.sin_addr.s_addr= INADDR_ANY;
91 sin.sin_family= AF_INET;
92
93 if (bind(sd, (struct sockaddr *)&sin,sizeof(struct sockaddr_in) ) != -1)
94 {
95 socklen_t addrlen= sizeof(sin);
96
97 if (listen(sd, 100) != -1)
98 {
99 if (getsockname(sd, (struct sockaddr *)&sin, &addrlen) != -1)
100 {
101 ret_port= sin.sin_port;
102 }
103 }
104 }
105 }
106
107 close(sd);
108 }
109
110 return ret_port;
111 }
112
113 } // namespace libtest