3 # A simple TCP client that sends some data and expects a response.
4 # Usage: tcp_client.pl HOSTNAME PORT DATA1 RESPONSE1
5 # DATA: hex-encoded data to send to the server
6 # RESPONSE: regexp that must match the server's response
12 # Pack hex digits into a binary string, ignoring whitespace.
16 return pack('H*', $hex);
19 ## Open a TCP connection to the specified host and port.
21 my ($host, $port) = @_;
22 my $socket = IO::Socket::INET->new(PeerAddr => $host,
26 die "Cannot connect to $host:$port: $!" unless $socket;
30 ## Close the TCP connection.
31 sub close_connection {
32 my ($connection) = @_;
33 $connection->shutdown(2);
34 # Ignore shutdown failures (at least for now)
38 ## Write the given data, expressed as hexadecimal
40 my ($connection, $hexdata) = @_;
41 my $data = parse_hex($hexdata);
43 while ($total_sent < length($data)) {
44 my $sent = $connection->send($data, 0);
46 die "Unable to send data: $!";
53 ## Read a response and check it against an expected prefix
55 my ($connection, $expected_hex) = @_;
56 my $expected_data = parse_hex($expected_hex);
58 while ($start_offset < length($expected_data)) {
60 my $ok = $connection->recv($actual_data, length($expected_data));
62 die "Unable to receive data: $!";
64 if (($actual_data ^ substr($expected_data, $start_offset)) =~ /[^\000]/) {
65 printf STDERR ("Received \\x%02x instead of \\x%02x at offset %d\n",
66 ord(substr($actual_data, $-[0], 1)),
67 ord(substr($expected_data, $start_offset + $-[0], 1)),
68 $start_offset + $-[0]);
71 $start_offset += length($actual_data);
77 print STDERR "Usage: $0 HOSTNAME PORT DATA1 RESPONSE1\n";
80 my ($host, $port, $data1, $response1) = @ARGV;
81 my $connection = open_connection($host, $port);
82 write_data($connection, $data1);
83 if (!read_response($connection, $response1)) {
86 close_connection($connection);