summaryrefslogtreecommitdiff
path: root/ndb/tools/old_dirs/ndbnet/lib/NDB/Util/SocketINET.pm
blob: faaa568a08e54b05e48a4cd6d97e01fd5843ecd3 (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
80
81
82
83
84
85
86
package NDB::Util::SocketINET;

use strict;
use Carp;
use Symbol;
use Socket;
use Errno;

require NDB::Util::Socket;

use vars qw(@ISA);
@ISA = qw(NDB::Util::Socket);

# constructors

my $log;

sub initmodule {
    $log = NDB::Util::Log->instance;
}

NDB::Util::SocketINET->attributes(
    host => sub { /^\S+$/ },
    port => sub { /^\d+$/ },
);

sub new {
    my $class = shift;
    @_ % 2 == 0 or confess 0+@_;
    my(%attr) = @_;
    my $socket = $class->SUPER::new(%attr,
	domain => PF_INET, type => SOCK_STREAM, proto => 'tcp')
	or $log->push, return undef;
    return $socket;
}

sub connect {
    my $socket = shift;
    @_ == 2 or confess 0+@_;
    my($host, $port) = @_;
    $port =~ /^\d+$/ or confess 'oops';
    my $iaddr = inet_aton($host);
    if (! $iaddr) {
	$log->put("host $host not found")->push($socket);
	return undef;
    }
    my $paddr = pack_sockaddr_in($port, $iaddr);
    $socket->SUPER::connect($paddr)
	or $log->push, return undef;
    $socket->sethost($host)
	or $log->push, return undef;
    $socket->setport($port)
	or $log->push, return undef;
    return 1;
}

sub bind {
    my $socket = shift;
    @_ == 1 or confess 0+@_;
    my($port) = @_;
    $port =~ /^\d+$/ or confess 'oops';
    my $paddr = pack_sockaddr_in($port, INADDR_ANY);
    $socket->SUPER::bind($paddr)
	or $log->push, return undef;
    $socket->setport($port)
	or $log->push, return undef;
    return 1;
}

sub acceptaddr {
    my $csocket = shift;
    @_ == 1 or confess 0+@_;
    my($paddr) = @_;
    my($port, $iaddr) = unpack_sockaddr_in($paddr);
    my $host = gethostbyaddr($iaddr, AF_INET);
    $csocket->sethost($host)
	or $log->push, return undef;
    $csocket->setport($port)
	or $log->push, return undef;
    $log->put("accept: host=%s port=%d",
	$csocket->gethost, $csocket->getport)->push($csocket)->debug;
    return 1;
}

1;
# vim:set sw=4: