socket TCP/IP for HTTP communcation - sockets

The following code is example php code for socket tutorial, and I run successfully to collect remote site or localhost webpage.Either the protocol number I used for socket_create is 0 or 6, both
number is also working on that code, Why ? I thought network programming will needs to include TCP and IP for today's window computer together to make the communication possible. Why just need TCP or IP protocol num could make the program code working that doesn't include both protocol num ?
TCP is protocol for transport layer and IP is protocol for network layer for both OSI or classical TCP/IP model
<?php
$protocol = 'tcp';
$get_prot = getprotobyname($protocol);
echo $get_prot."----protocol\n";
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 6)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
if(!socket_connect($sock , '127.0.0.1' , 80))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not connect: [$errorcode] $errormsg \n");
}
echo "Connection established \n";
$message = "GET / HTTP/1.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 \r\n\r\n";
$message = "GET / HTTP/1.1\r\n";
$message .= "Host: \r\n";
$message .= "Connection: Close\r\n\r\n";
//Send the message to the server
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n");
}
echo "Message send successfully \n";
//Now receive reply from server
if(socket_recv ( $sock , $buf , 6144 , MSG_WAITALL ) === FALSE)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
//print the received message
echo $buf;
?>

Passing 0 as the protocol will give you a default protocol. AF_INET says you want
IP protocol suite (IPv4 specifically). For a combination of AF_INET and SOCK_STREAM, tcp is the default. A combination of AF_INET6 and SOCK_DGRAM would give you IPv6 and UDP as default.
TCP has the protocol number 6, which you can pass as well if you want to be explicit.

Related

perl6 IO::Socket::INET Could not receive data from socket: Connection reset by peer

Sample server:
#!/usr/bin/env perl6
my $listen = IO::Socket::INET.new(:listen, :localhost<localhost>, :localport(3333));
loop {
my $conn = $listen.accept;
while my $buf = $conn.recv(:bin) {
$conn.write: $buf;
}
$conn.close;
}
Client:
#!/use/bin/env perl6
my $c = IO::Socket::INET.new(:host<localhost>, :port(3333));
$c.print: "{time}\n";
#say $c.recv; #commented out on purpose
sleep 1 ;
$c.close ;
server error:
Could not receive data from socket: Connection reset by peer
in block <unit> at server4.p6 line 5
In the server on each of the blocks I tried CATCH and QUIT. How should I catch this error?
Server needs to catch the error in the loop block:
#!/usr/bin/env perl6
my $listen = IO::Socket::INET.new(:listen, :localhost<localhost>, :localport(3333));
loop {
my $conn = $listen.accept;
while my $buf = $conn.get {
$conn.print: $buf;
}
$conn.close;
CATCH { default { say .^name, ': ', .Str , " handled in $?LINE";}}
}
Output of server reports the error and stays running to accept new connections:
perl6 --ll-exception server.p6
X::AdHoc: Could not receive data from socket: Connection reset by peer handled in 9

How to connect outlook IMAP server go through proxy server uisng perl

I want to connect IMAP server but i am not able to connect directly imap server that's why i used proxy but still i am not able to connect and read emails.
Following is my code,
#!/usr/intel/bin/perl
use strict;
use warnings;
# fill in your details here
my $username = 'username#companyname.com';
my $password = 'password';
my $mailhost = 'outlook.office365.com';#imap-mail.outlook.com
my $mailport = 993;
my $proxyhost = '121.244.253.5';
my $proxyport = 8080;
print "Proxy...\n";
use IO::Socket::Socks::Wrapper(
{
ProxyAddr => $proxyhost,
ProxyPort => $proxyport,
SocksDebug => 0,
Timeout => 100000000
}
);
# required modules
use Net::IMAP::Simple;
use Email::Simple;
use IO::Socket::SSL;
print "Connecting...\n";
$IO::Socket::SSL::DEBUG=2;
# Connect
my $imap = Net::IMAP::Simple->new(
$mailhost,
port => $mailport,
use_ssl => 1
) || die "Unable to connect to IMAP: $Net::IMAP::Simple::errstr \n";
print "Logging In...\n";
# Log in
if ( !$imap->login( $username, $password ) ) {
print STDERR "Login failed: " . $imap->errstr . "\n";
exit(64);
}
print "Selecting Folder...\n";
# Look in the the INBOX
my $nm = $imap->select('Archive');
print "How Many Messages Are There...\n";
# How many messages are there?
my ($unseen, $recent, $num_messages) = $imap->status();
print "unseen: $unseen, recent: $recent, total: $num_messages\n\n";
print "Quickly Look for unseen messages...\n";
## Iterate through unseen messages
for ( my $i = 1 ; $i <= $nm ; $i++ ) {
if ( $imap->seen($i) ) {
next;
} else {
my $es = Email::Simple->new( join '', #{ $imap->top($i) } );
printf( "[%03d] %s\n\t%s\n", $i, $es->header('From'), $es->header(+'Subject') );
}
}
print "Disconnect...\n";
# Disconnect
$imap->quit;
print "Exit...\n";
exit;
Following is my Response :-
Proxy...
Connecting...
DEBUG: .../IO/Socket/SSL.pm:332: socket not yet connected
DEBUG: .../IO/Socket/SSL.pm:334: socket connected
DEBUG: .../IO/Socket/SSL.pm:347: ssl handshake not started
DEBUG: .../IO/Socket/SSL.pm:377: set socket to non-blocking to enforce timeout=100000000
I don't know why its not going further. Please share your opinion and correct me.
Please help me here...
Correct syntax is :
my $proxyhost = '65.130.4.202';
my $proxyport = 24451;
use Net::IMAP::Simple;
print "Proxy...\n";
use IO::Socket::Socks::Wrapper(
Net::IMAP::Simple => {
ProxyAddr => $proxyhost,
ProxyPort => $proxyport,
SocksDebug => 3,
Timeout => 100000000
}
);
use IO::Socket::SSL;
print "Connecting...\n";
$IO::Socket::SSL::DEBUG=2;
# Connect
my $imap = Net::IMAP::Simple->new(
'imap.gmail.com',
port => 993,
use_ssl => 1
) || die "Unable to connect to IMAP: $Net::IMAP::Simple::errstr \n";
print "Logging In...\n";
# Log in
if ( !$imap->login( 'pappucant#gmail.com', 'pappu123' ) ) {
print STDERR "Login failed: " . $imap->errstr . "\n";
exit(64);
}
Working fine for me, didn't work with the proxy server mentioned in the code.
Output:
Proxy...
Connecting...
DEBUG: .../IO/Socket/SSL.pm:625: socket not yet connected
DEBUG: .../IO/Socket/SSL.pm:627: socket connected
DEBUG: .../IO/Socket/SSL.pm:649: ssl handshake not started
DEBUG: .../IO/Socket/SSL.pm:682: using SNI with hostname imap.gmail.com
DEBUG: .../IO/Socket/SSL.pm:738: set socket to non-blocking to enforce timeout=90
DEBUG: .../IO/Socket/SSL.pm:764: ssl handshake in progress
DEBUG: .../IO/Socket/SSL.pm:774: waiting for fd to become ready: SSL wants a read first
DEBUG: .../IO/Socket/SSL.pm:794: socket ready, retrying connect
DEBUG: .../IO/Socket/SSL.pm:764: ssl handshake in progress
DEBUG: .../IO/Socket/SSL.pm:774: waiting for fd to become ready: SSL wants a read first
DEBUG: .../IO/Socket/SSL.pm:794: socket ready, retrying connect
DEBUG: .../IO/Socket/SSL.pm:764: ssl handshake in progress
DEBUG: .../IO/Socket/SSL.pm:774: waiting for fd to become ready: SSL wants a read first
DEBUG: .../IO/Socket/SSL.pm:794: socket ready, retrying connect
DEBUG: .../IO/Socket/SSL.pm:809: ssl handshake done
Logging In...
Login failed: [AUTHENTICATIONFAILED] Invalid credentials (Failure)

socket_select method in php

could any one help me to understand the following example about handling multiple connection in PHP socket programming.
I need just to explain for me these steps
if(socket_select($read , $write , $except , null) === false)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
//if ready contains the master socket, then a new connection has come in
if (in_array($sock, $read))
{
}
really I cant understand what happen in those steps.
this is the full example :
error_reporting(~E_NOTICE);
set_time_limit (0);
$address = "0.0.0.0";
$port = 6000;
$max_clients = 10;
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if( !socket_bind($sock, $address , 5000) )
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
if(!socket_listen ($sock , 10))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
echo "Socket listen OK \n";
echo "Waiting for incoming connections... \n";
//array of client sockets
$client_socks = array();
//array of sockets to read
$read = array();
//start loop to listen for incoming connections and process existing connections
while (true)
{
//prepare array of readable client sockets
$read = array();
//first socket is the master socket
$read[0] = $sock;
//now add the existing client sockets
for ($i = 0; $i < $max_clients; $i++)
{
if($client_socks[$i] != null)
{
$read[$i+1] = $client_socks[$i];
}
}
//now call select - blocking call
if(socket_select($read , $write , $except , null) === false)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
//if ready contains the master socket, then a new connection has come in
if (in_array($sock, $read))
{
for ($i = 0; $i < $max_clients; $i++)
{
if ($client_socks[$i] == null)
{
$client_socks[$i] = socket_accept($sock);
//display information about the client who is connected
if(socket_getpeername($client_socks[$i], $address, $port))
{
echo "Client $address : $port is now connected to us. \n";
}
//Send Welcome message to client
$message = "Welcome to php socket server version 1.0 \n";
$message .= "Enter a message and press enter, and i shall reply back \n";
socket_write($client_socks[$i] , $message);
break;
}
}
}
//check each client if they send any data
for ($i = 0; $i < $max_clients; $i++)
{
if (in_array($client_socks[$i] , $read))
{
$input = socket_read($client_socks[$i] , 1024);
if ($input == null)
{
//zero length string meaning disconnected, remove and close the socket
unset($client_socks[$i]);
socket_close($client_socks[$i]);
}
$n = trim($input);
$output = "OK ... $input";
echo "Sending output to client \n";
//send response to client
socket_write($client_socks[$i] , $output." welcome any time");
}
}
}

multiple socket_read with multi clients in php

i have a problem with socket connections
i need multiple socket read with several clients but i can connect several clients but only can one socket_read for client, if i add second socket_read, the program doesnt work
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
$socket_bind($sock, $address , $port);
$socket_listen ($sock , 10)
while (true){
$read = array();
//first socket is the master socket
$read[0] = $sock;
//now add the existing client sockets
for ($i = 0; $i < $max_clients; $i++)
{
if($client_socks[$i] != null)
{
$read[$i+1] = $client_socks[$i];
}
}
//now call select - blocking call
if(socket_select($read , $write , $except , null) === false)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
//if ready contains the master socket, then a new connection has come in
if (in_array($sock, $read))
{
for ($i = 0; $i < $max_clients; $i++)
{
if ($client_socks[$i] == null)
{
$client_socks[$i] = socket_accept($sock);
//display information about the client who is connected
if(socket_getsockname($client_socks[$i], $address, $port))
{
echo "Client $i : $port . \n";
}
//Send Welcome message to client
$msg = "Bienvenido cliente {$key[0]} \n\r";
$msg .= "1.-Crear Paleta\n\r";
$msg .= "2.-Ubicar Paleta\n\r";
$msg .= "exz.-Salir\n\r";
socket_write($client_socks[$i] , $msg);
break;
}
}
}
//check each client if they send any data
for ($i = 0; $i < $max_clients; $i++)
{
if (in_array($client_socks[$i] , $read))
{
if (false === ($input = socket_read($client_socks[$i],PHP_NORMA))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
echo "client $i : ";
echo "$input";
//send response to client
socket_write ($client_socks[$i], "client $i : ");
socket_write ($client_socks[$i], $input);
socket_write ($client_socks[$i], "\r");
$y++;
}
}
}

Feedback service for Push notification

I wrote the below script to read the feedback data. But, for some reasons, I am not receiving any data from the server. Can you kindly let me know whats wrong with the script. Also, if you have any working php script for feedback service, can you kindly share it...
regards,
DD.
<?php
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
// Set time limit to indefinite execution
set_time_limit (0);
// Set the ip and port we will listen on
$address = 'ssl://feedback.sandbox.push.apple.com';
$port = 2196;
// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
echo "PHP Socket Server started at " . $address . " " . $port . "\n";
// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address');
// Start listening for connections
socket_listen($sock);
//loop and listen
while (true) {
/* Accept incoming requests and handle them as child processes */
$client = socket_accept($sock);
// Read the input from the client – 1024 bytes
$input = socket_read($client, 1024);
}
// Close the client (child) socket
socket_close($client);
// Close the master sockets
socket_close($sock);
?>
You must act as a client, just like you're sending notification. That must be something like:
<?php
$certFile = 'apns-dev.pem';
while (true) {
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $certFile);
//stream_context_set_option($ctx, 'ssl', 'passphrase', $this->certPass);
echo "try to open stream\n";
$fp = stream_socket_client('ssl://feedback.sandbox.push.apple.com:2196', $err, $errstr, 5, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
print "Failed to connect". $err . $errstr. "\n";
exit();
} else {
echo 'Connected to feedback sandbox...';
while (($in = fread($fp, 1024)) != EOF) {
echo 'read '. $in . "\n";
}
socket_close($fp);
fclose($fp);
}
sleep(2000);
}
?>