Network Protocol 11 - Socket Programming

Links to the original text: https://www.cnblogs.com/BeiGuo-FengGuang/p/10088410.html

Before that, we had a basic understanding of most protocols in network communication, which has always been in the process of "listening". Many people will feel as if they understand, but when they close the page and recall, they seem to know nothing. This time, let's code the "real gun and live ammunition", and then use a "magic weapon" - network analysis system to track the life course of the data packet in detail, so that our theory can be truly presented, bloggers who are interested in network communication can also carry the system analysis once, you will certainly get a lot of results.

I don't say much about it, just go to the code. Interested bloggers can make relevant rewriting according to various programming languages, and then take our analysis system to see the real network communication process.

Local request forwarded to gateway

192.168.1.10 in the code is another server in the intranet, and the IP of the landlord is 192.168.1.73. When running the server locally, a routing configuration should be made, otherwise the analysis system can not grab the relevant packages. Under window s, you can configure it as follows:

  1. Open DOS window as administrator.
  2. route add native ip mask 255.255.255.255 gateway ip (route forwarding, remember? Forget about it? Order me, order me.);

What? I don't know how to check IP and gateway? Let me tell you
Remember to delete the forwarding rules when the operation is completed. Otherwise, you will find that requests from the local computer will become very slow.
Examples:

// Adding routing and forwarding rules
route add 192.168.1.73 mask 255.255.255.255 192.168.1.1 

// Delete forwarding rules
route delete 192.168.1.73

Socket Based on TCP

_Server:

<?php
/**
 * 1. socket_create: New socket
 * 2. socket_bind:   Binding IP and port
 * 3. socket_listen: Monitor
 * 4. socket_accept: Receive client connection and return connection socket
 * 5. socket_read:   Read Client Send Data
 * 6. socket_write:  Return data
 * 7. socket_close:  Close socket
 */

$ip = '192.168.1.10';
$port = 23333;
// $port = 80;
$sk = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
!$sk && outInfo('socket_create error');

// Binding IP
!socket_bind($sk, $ip, $port) && outInfo('socket_bind error');

// Monitor
!socket_listen($sk) && outInfo('sever listen error');

outInfo("Success Listen: $ip:$port", 'INFO');
while (true) {
    $accept_res = socket_accept($sk);
    !$accept_res && outInfo('sever accept error');
    $reqStr = socket_read($accept_res, 1024);

    if (!$reqStr) outInfo('sever read error');
    outInfo("Server receive client msg: $reqStr", 'INFO');
    $response = 'Hello A, I am B. you msg is : ' . $reqStr . PHP_EOL;
    if (socket_write($accept_res, $response, strlen($response)) === false) {
        outInfo('response error');
    }

    socket_close($accept_res);
}

socket_close($sk);

function outInfo($errMsg, $level = 'ERROR')
{
    if ($level === 'ERROR') {
        $errMsg = "$errMsg, msg: " . socket_strerror(socket_last_error());
    }
    echo $errMsg . PHP_EOL;
    $level === 'ERROR' && die;
}

_Client:

<?php
/**
 * 1. socket_create:  New socket
 * 2. socket_connect: Connect the server
 * 3. socket_write:   Send data to the server
 * 4. socket_read:    Read the data returned by the server
 * 5. socket_close:   Close socket
 */

$ip = '192.168.1.10';
$port = 23333;
$sk = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
!$sk && outInfo('socket_create error');

!socket_connect($sk, $ip, $port) && outInfo('connect fail');
$msg = 'hello, I am A';

if (socket_write($sk, $msg, strlen($msg)) === false) {
    outInfo('socket_write fail');
}

while ($res = socket_read($sk, 1024)) {
    echo 'server return message is:'. PHP_EOL. $res;
}

socket_close($sk);//Close socket flow after work

function outInfo($errMsg, $level = 'ERROR')
{
    if ($level === 'ERROR') {
        $errMsg = "$errMsg, msg: " . socket_strerror(socket_last_error());
    }
    echo $errMsg . PHP_EOL;
    $level === 'ERROR' && die;
}

The above code is based on PHP native Socket, and other languages have corresponding Socket operation functions, which can be rewritten. Mainly the following analysis process.

As shown above, this is all the data transmission process captured by our analysis system. You can really see what happens at each step and the corresponding state changes (the picture is bigger, right-click is recommended to open it in the new tab).

In the first half of the graph, we can see that the analysis system divides the whole TCP life course into three stages: establishing connection, trading and closing connection. This is completely consistent with our previous theoretical knowledge.
The transaction sequence diagram in the lower left corner of the

UDP-based Socket

<?php
/**
 * 1. socket_create:   New socket
 * 2. socket_bind:     Binding IP and port
 * 3. socket_recvfrom: Read Client Send Data
 * 4. socket_sendto:   Return data
 * 5. socket_close:    Close socket
 */

$ip = '192.168.1.10';
$port = 23333;
$sk = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
!$sk && outInfo('socket_create error');

// Binding IP
!socket_bind($sk, $ip, $port) && outInfo('socket_bind error');

outInfo("Success Listen: $ip:$port", 'INFO');
while (true) {
    $from = '';
    $reqPort = 0;
    if (!socket_recvfrom($sk, $buf, 1024, 0, $from, $reqPort)) {
        outInfo('sever socket_recvfrom error');
    }

    outInfo("Received msg $buf from remote address $from:$port", 'INFO');
    $response = "Hello $from:$port, I am Server. your msg : " . $buf . PHP_EOL;
    if (!socket_sendto($sk, $response, strlen($response), 0, $from, $reqPort)) {
        outInfo('socket_sendto error');
    }
}

socket_close($sk);

function outInfo($errMsg, $level = 'ERROR')
{
    if ($level === 'ERROR') {
        $errMsg = "$errMsg, msg: " . socket_strerror(socket_last_error());
    }
    echo $errMsg . PHP_EOL;
    $level === 'ERROR' && die;
}

Client:

<?php
/**
 * 1. socket_create:  New socket
 * 2. socket_write:   Send data to the server
 * 3. socket_read:    Read the data returned by the server
 * 4. socket_close:   Close socket
 */

$ip = '192.168.1.10';
$port = 23333;
$sk = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
!$sk && outInfo('socket_create error');

$msg = 'hello, I am A';

if (!socket_sendto($sk, $msg, strlen($msg), 0, $ip, $port)) {
    outInfo('socket_sendto fail');
}

$from = '';
$reqPort = 0;
if (!socket_recvfrom($sk, $buf, 1024, 0, $from, $reqPort)) {
    outInfo('server socket_recvfrom error');
}

outInfo("Received $buf from server address $from:$port", 'INFO');

socket_close($sk);

function outInfo($errMsg, $level = 'ERROR')
{
    if ($level === 'ERROR') {
        $errMsg = "$errMsg, msg: " . socket_strerror(socket_last_error());
    }
    echo $errMsg . PHP_EOL;
    $level === 'ERROR' && die;
}

UDP packet analysis diagram:

As shown above, UDP data package analysis chart is much simpler than TCP obviously. People are simple, let alone talk about it. However, it should be noted that when writing code, UDP server should never close Socket in the loop.

Introduction of Analysis System

The analysis system used above is called Kelai Network Analysis System. Click on me to download . The analysis system is conscientious and provides a free technical exchange version. Interested partners can download and play, very powerful.

 

Welcome to add personal micro-signals: Like as he thinks.

Welcome to pay attention to my public number, not only recommend the latest blog for you, but also more surprises and resources are waiting for you! Learn together and make progress!

 

 

Tags: socket network PHP Programming

Posted on Mon, 26 Aug 2019 05:09:56 -0700 by haagen