Testsuite: move dynamic_socket to Exim::Runtest
[exim.git] / test / lib / Exim / Runtest.pm
1 package Exim::Runtest;
2 use strict;
3 use warnings;
4 use IO::Socket::INET;
5 use Carp;
6
7 use List::Util qw'shuffle';
8
9
10 # find a group name, preferrable 'mail', but
11 # use some other random name if 'mail' isn't a valid group
12 # name
13 sub mailgroup {
14     my $group = shift;
15
16     croak "Need a group *name*, not a numeric group id."
17         if $group =~ /^\d+$/;
18
19     return $group if getgrnam $group;
20
21     my @groups;
22     setgrent or die "setgrent: $!\n";
23     push @groups, $_ while defined($_ = getgrent);
24     endgrent;
25     return (shuffle @groups)[0];
26 }
27
28 sub dynamic_socket {
29     my $socket;
30     for (my $port = 1024; $port < 65000; $port++) {
31         $socket = IO::Socket::INET->new(
32             LocalHost => '127.0.0.1',
33             LocalPort => $port,
34             Listen => 10,
35             ReuseAddr => 1,
36         ) and return $socket;
37     }
38     croak 'Can not allocate a free port.';
39 }
40
41 1;