TheVend has asked for the wisdom of the Perl Monks concerning the following question:
Server: Echo's back to client the clients IP address. Logs the clients IP address.
Client: Attempts to connect to server and if successful displays the servers echoed IP.
I have some “borrowed” server code but can’t seem to get it to echo the connected clients IPSERVER
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"; 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; 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 "Connection recieved from $name\n"; close NEW_SOCKET; }
CLIENT
use strict; use Socket; # 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; while ($line = <SOCKET>) { print "$line\n"; } close SOCKET or die "close: $!";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Client Server
by AppleFritter (Vicar) on Jul 09, 2014 at 21:06 UTC | |
by Anonymous Monk on Jul 09, 2014 at 22:55 UTC | |
by TheVend (Novice) on Jul 15, 2014 at 17:28 UTC | |
by AppleFritter (Vicar) on Jul 15, 2014 at 18:11 UTC | |
by Anonymous Monk on Jul 15, 2014 at 18:30 UTC | |
|
Re: Client Server
by sn1987a (Curate) on Jul 09, 2014 at 19:57 UTC |