Perl HTTP server not reading requests from clients - perl

I have created an HTTP server in Perl to accept requests from clients.
At the moment only one client is sending the request.
This is how my set-up is:
Client --> Server (this is proxy server as well connecting to the internet), Apache 2 running on Ubuntu.
This is the Perl code for my server:
#!/usr/bin/perl
use IO::Socket::INET;
use strict;
use warnings;
use LWP::Simple;
# auto-flush on socket
$| = 1;
my $port = 7890;
# Create a listening port
my $socket = new IO::Socket::INET(
LocalHost => '127.0.0.1',
LocalPort => shift || $port,
Proto => 'tcp',
Listen => SOMAXCONN,
Reuse => 1
) or die "cannot create socket $!\n";
# open a file and write client requests to the file
$| = 1;
open(FH, '>>', '/home/suresh/clientrequest.txt')
or die "could not open the /home/suresh/clientrequest : $!\n";
print FH "server waiting for client on port\n"
or die "could not write to file : $!\n";
while (my $client_socket = $socket->accept()) {
$client_socket->autoflush(1);
#print FH "Welcome to $0 \n";
my $client_address = $socket->peerhost();
my $client_port = $client_socket->peerport();
print FH "connection from $client_address:$client_port\n";
# read from connected client
my $data = "";
$client_socket->recv($data, 1024);
print FH "Data received from $client_address:$client_port: $data\n";
# write response data to the client
$data = "Sucessfully processed your request";
$client_socket->send($data);
shutdown($client_socket, 1);
}
close(FH);
$socket->close();
When I bring this server up and try sending a request from a client, the request is written to the file, so it looks like the requests are captured by the server.
Can anyone please let me know what other configurations I need to do at server side and at client?

If you write
$| = 1;
then flushing is only activated for the default output filehandle. This is STDOUT unless changed with the select() builtin. So FH is not flushed here — I guess this was your intention. Instead, you have to write
FH->autoflush(1);

Related

In perl socket programming how to send a data from client and receive it from server

I am using Socket module to perform socket programming in Perl.And now I want to send one data from the client and receive it from the Server side. How I will achive this. Please help.
Given below in the code i used
server
#!/usr/bin/perl -w
# Filename : server.pl
use strict;
use IO::Socket;
use Socket;
use Sys::Hostname;
use constant BUFSIZE => 1024;
# use port 7890 as default
my $port = shift || 7890;
my $proto = getprotobyname('tcp');
my $server = "localhost"; # Host IP running the server
# create a socket, make it reusable
socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
or die "Can't open socket $!\n";
setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)
or die "Can't set socket option to SO_REUSEADDR $!\n";
# bind to a port, then listen
bind( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
or die "Can't bind to port $port! \n";
listen(SOCKET, 5) or die "listen: $!";
print "SERVER started on port $port\n";
# accepting a connection
my $client_addr;
my $val = 100;
while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
# send them a message, close connection
my $name = gethostbyaddr($client_addr, AF_INET );
print NEW_SOCKET "Smile from the server";
print NEW_SOCKET $val;
print "Connection recieved from $name\n";
close NEW_SOCKET;
}
client
#!/usr/bin/perl -w
# Filename : client.pl
use strict;
use IO::Socket;
use Socket;
use Sys::Hostname;
use constant BUFSIZE => 1024;
# initialize host and port
my $host = shift || 'localhost';
my $port = shift || 7890;
my $server = "localhost"; # Host IP running the server
# create the socket, connect to the port
socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2])
or die "Can't create a socket $!\n";
connect( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
or die "Can't connect to port $port! \n";
my $line;
my $req = 1000;
while ($line = <SOCKET>) {
print "$line\n";
}
close SOCKET or die "close: $!";
Here is a basic example. The code below adds to what you have, but please note that modules IO::Socket::IP or core IO::Socket::INET make it easier than the lower level calls you use.
The only changes to your code (other than shown below) are from SOCKET to lexical my $socket, and an existing declaration is moved inside the while condition.
Every server-client system needs a protocol, an arrangement of how the messages are exchanged. Here, once the client connects the server sends a message and then they exchange single prints.
server.pl
# ... code from the question, with $socket instead of SOCKET
use IO::Handle; # for autoflush
while (my $client_addr = accept(my $new_socket, $socket))
{
$new_socket->autoflush;
my $name = gethostbyaddr($client_addr, AF_INET );
print "Connection received from $name\n";
print $new_socket "Hello from the server\n";
while (my $recd = <$new_socket>) {
chomp $recd;
print "Got from client: $recd\n";
print $new_socket "Response from server to |$recd|\n";
}
close $new_socket;
}
Instead of loading IO::Handle you can make a handle hot (autoflush) using select.
client.pl
I add a counter $cnt to simulate some processing that leads to a condition to break out.
# ... same as in question, except for $socket instead of SOCKET
use IO::Handle;
$socket->autoflush;
my $cnt = 0;
while (my $line = <$socket>) {
chomp $line;
print "Got from server: $line\n";
last if ++$cnt > 3; # made up condition to quit
print $socket "Hello from client ($cnt)\n";
}
close $socket or die "close: $!";
This behaves as expected. The client exits after three messages, the server stays waiting. If you wish to indeed write just once the simple print and read replace the while loops.
The exchanges can be far more sophisticated, see the example in perlipc linked at the end.
A few comments
Using the mentioned modules makes this much easier
Any glitch in flushing can lead to deadlocks, where one party wrote and is waiting to read, while the other did not get the message still sitting in the pipe and is thus, also, waiting to read
Check everything. All checking is left out for brevity
use warnings; is better than the -w switch. See the discussion on warnings page
This is only meant to answer the question of how to enable communication between them. One good resource for study is perlipc, which also has a full example. The docs for involved modules provide a lot of information as well.

no data received on server side when data is written to socket on client side

I send "smile from server" to the client and expect "good morning" from the client. Basically I don't understand whether the flaw is on server side or the client side.
here is my code :
Server side
#!/usr/bin/perl -w
# Filename : server.pl
use strict;
use Socket;
# use port 7890 as default
my $port = shift || 7890;
my $proto = getprotobyname('tcp');
my $server = "localhost"; # Host IP running the server
# create a socket, make it reusable
socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
or die "Can't open socket $!\n";
# bind to a port, then listen
bind( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
or die "Can't bind to port $port! \n";
listen(SOCKET, 5) or die "listen: $!";
print "SERVER started on port $port\n";
# accepting a connection
my $client_addr;
while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
# send them a message, close connection
my $name = gethostbyaddr($client_addr, AF_INET );
print NEW_SOCKET "Smile from the server";
sleep(5);
print <NEW_SOCKET>;
print "Connection recieved from $name\n";
close NEW_SOCKET;
}
and this is the client side:
#!/usr/bin/perl -w
use strict;
use Socket;
# initialize host and port
my $host = 'localhost';
my $port = 7890;
my $server = "localhost"; # Host IP running the server
# create the socket, connect to the port
socket(SOCKET,PF_INET,SOCK_STREAM,getprotobyname('tcp'))
or die "Can't create a socket $!\n";
connect( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
or die "Can't connect to port $port! \n";
my $line;
while ($line = <SOCKET>) {
print "$line\n";
print SOCKET "good morning";
sleep(10);
}
close SOCKET or die "close: $!";
Buffering.
It's hard to show an example of how to turn the buffering off, when you're using global filehandles and lowlevel core socket functions, instead of using a higher-level IO::Handle-derived socket wrapper.
If instead you'd use that, then this would be simple. The server would then be:
use strict;
use IO::Socket::IP;
# use port 7890 as default
my $port = shift || 7890;
my $listensock = IO::Socket::IP->new(
LocalPort => $port,
Listen => 5,
) or die "Cannot listen - $#";
# accepting a connection
while (my ($client, $client_addr) = $listensock->accept) {
$client->autoflush(1); ### THIS IS THE KEY LINE
# send them a message, close connection
$client->print("Smile from the server");
sleep(5);
print <$client>;
}
The key point being the call to autoflush here, which disables the output buffering and makes sure to send all bytes immediately.
$client->print("Smile from the server\n");
'\n' is the end ch for getline

Working of perl sockets

I am a beginner to Perl socket programming. As of now, the server sends a string and the client responds with another string in my program. Later, if the server sends another string, the client is not able to receive it. To transfer data between the server and client for multiple times, should I include any functions?
SERVER:
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::INET;
my $socket;
my $clientsocket;
my $serverdata;
my $clientdata;
$socket = new IO::Socket::INET (
LocalHost => '127.0.0.1',
LocalPort => 2500,
Proto => 'tcp',
Listen => 1,
Reuse => 1
) or die "Oops: $! \n";
print "Waiting for the Client.\n";
$clientsocket = $socket->accept();
print "Connected from : ", $clientsocket->peerhost();
print ", Port : ", $clientsocket->peerport(), "\n";
# Write some data to the client
$serverdata = "This is the Server speaking \n";
print $clientsocket "$serverdata \n";
# read the data from the client
$clientdata = <$clientsocket>;
print "$clientdata";
$serverdata = "Server Again writing \n";
print $clientsocket "$serverdata";
$socket->close();
CLIENT:
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::INET;
use Tk;
my $socket;
my $serverdata;
$socket = new IO::Socket::INET (
PeerHost => '127.0.0.1',
PeerPort => '2500',
Proto => 'tcp',
) or die "$!\n";
print "Connected to the Server.\n";
# read the message sent by server.
$serverdata = <$socket>;
print "Message from Server : $serverdata \n";
# Send some message to server.
my $name = "Client here!";
print $socket "$name";
# Read message sent by server.
$serverdata = <$socket>;
print "$serverdata";
$socket->close();
Printing of $serverdata second time in the Client side is not happening.
If you use to read message from another end, the sender must end the message with "\n".
Alternatively, you can use recv(...) so the message won't be buffered till newline character.
Just make sure your client sends a whole line. SInce you are reading with
<$clientsocket>
your server waits for a "\n" from the client.
Your server starts listening on some port. It waits until a client connects, the accepts that connection. It reads and writes a bit of data over the client connection. And then? Then it just closes the socket and exits the program.
That is not what you intended: You want the server to start waiting for the next connection. That means some kind of loop: Each time a client connects, we'll do our communication:
while (my $client = $socket->accept) {
# do something with the $client
}
I recommend you read through the relevant sections of perldoc perlipc, but keep in mind it uses outdated best practices, so don't directly copy anything.

2 way communication between Client-Server Scripts through Perl

REQUIREMENTS:
The s.erver waits for connection.
Once the client runs, the connection through the socket is developed successfully.
The Server reads a text file and sends the message to the Client.
The Client listens to it and prints it.
The Client reads a text file sends the message (acknowledgement) to the Server.
The Server listens to it and prints it.
Here is the solution to the above mentioned problem:
SERVER SCRIPT:
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::INET;
my $socket;
my $clientsocket;
my $serverdata;
my $clientdata;
$socket = new IO::Socket::INET (
LocalHost => '127.0.0.1',
LocalPort => '0155',
Proto => 'tcp',
Listen => 1,
Reuse => 1
) or die "Oops: $! \n";
print "Waiting for the Client.\n";
$clientsocket = $socket->accept();
print "Connected from : ", $clientsocket->peerhost(); # Display messages
print ", Port : ", $clientsocket->peerport(), "\n";
# Write some data to the client
$serverdata = "This is the Server speaking :)\n";
print $clientsocket "$serverdata \n";
# read the data from the client
$clientdata = <$clientsocket>;
print "Message received from Client : $clientdata\n";
$socket->close();
CLIENT SCRIPT:
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::INET;
my $socket;
my $serverdata;
my $clientdata;
$socket = new IO::Socket::INET (
PeerHost => '127.0.0.1',
PeerPort => '0155',
Proto => 'tcp',
) or die "$!\n";
print "Connected to the Server.\n";
# read the message sent by server.
$serverdata = <$socket>;
print "Message from Server : $serverdata \n";
# Send some message to server.
$clientdata = "This is the Client speaking :)";
print $socket "$clientdata \n";
$socket->close();

Remote command execution using perl client-server (socket)

My client.pl
#!/usr/bin/perl
use IO::Socket::INET;
use strict;
my $name = '172.20.10.189'; #Server IP
my $port = '7890';
my $socket = IO::Socket::INET->new('PeerAddr' => $name,
'PeerPort' => $port,
'Proto' => 'tcp') or die "Can't create socket ($!)\n";
print "Client sending\n";
while (1) {
my $msg = <STDIN>;
print $socket $msg;
print scalar <$socket>;
}
close $socket
or die "Can't close socket ($!)\n";
My server.pl
#!/usr/bin/perl
use IO::Socket::INET;
use strict;
my $port = "7890";
my $socket = IO::Socket::INET->new('LocalPort' => $port,
'Proto' => 'tcp',
'Listen' => SOMAXCONN)
or die "Can't create socket ($!)\n";
while (my $client = $socket->accept) {
my $name = gethostbyaddr($client->peeraddr, AF_INET);
my $port = $client->peerport;
while (<$client>) {
print "[$name $port] $_";
my #out = `$_`;
print #out;
print $client "$.: #out";
}
close $client
or die "Can't close ($!)\n";
}
die "Can't accept socket ($!)\n";
My client is sending a command (ls -lrt /) to the server and Server is supposed to run that command and send output to the client back.
Problem:-
The command is executed successfully on the server but it sends only first line to the client. If I press any key from client again the next line of output is sent to the client.
Or tell me how to send multiple line output to back to client.
Any help would be appreciated.
Thanks
Abhishek
The Server sends all lines to the client, the client however chooses to read only one line:
print scalar <$socket>;
If you remove the scalar, it should work. However, your architecture is still a security nightmare.
All servers should run in taint mode (-T switch).
Never blindly execute commands that a clients sends you. Only execute commands that pass a very strict validation test, do not run commands that just don't look malicious.
Perhaps you are trying to duplicate SSH, you might want to look at that program instead.
Your server doesn't do any kind of authentication. At least it logs all inputs.
It was a silly mistake... and I have fixed the first issue as follows and got multi-line output on the client side...
Client.pl
#!/usr/bin/perl
use IO::Socket::INET;
use strict;
my $name = '172.20.10.189'; #Server IP
my $port = '7890';
my $socket = IO::Socket::INET->new('PeerAddr' => $name,
'PeerPort' => $port,
'Proto' => 'tcp')
or die "Can't create socket ($!)\n";
print "Client sending\n";
while (1) {
my $msg = <STDIN>;
print $socket $msg;
while (<$socket>)
{
print "\n$_";
}
}
close $socket
or die "Can't close socket ($!)\n";
BUT there is one more issue -
I want my client to keep sending few other commands one after another until I close the client manually and receive output.
The problem is - It receives output of the first command only..
Can anyone now help me on this?