Home Backend Development PHP Tutorial 100 lines of PHP code to implement socks5 proxy server

100 lines of PHP code to implement socks5 proxy server

Jul 29, 2016 am 08:51 AM
data remote socket stream this

Two days ago, I saw a guy on Station B trying to assemble a computer for 100 yuan to play LOL with smooth graphics. I suddenly thought that 100 lines of code could (simplely) achieve something fun. I mainly do PHP development, so I have this article.

Of course, since PHP (not counting swoole extension) itself is not good at network server programming, this proxy is just a toy, a little far away from daily use. If you want to use a stable and reliable encryption (so you can learn to surf the Internet) proxy, you can use this: https://github.com/momaer/asocks-go is also 100 lines of code and implemented using go.

During the writing process, I found that PHP multi-threading is still difficult. For example, I started to want to create a new thread for each connection. But this thread must be saved (for example, saved in an array), such as this one in the official example: https://github.com/krakjoe/pthreads/blob/master/examples/SocketServer.phpIt should be placed in the $clients array , otherwise, you can try (curl -L an address that requires 301) and you will know what happens.

This example says that in the real world, do something here to ensure clients not running are destroyed. However, it does not talk about how to destroy connections that are no longer running. kindness. I tried putting $clients into a class, passing the class to the thread class, and then unsetting the corresponding connection in $clients when the thread class was about to end, to no avail.

Then, the following is a proxy implemented using a thread pool. Logically speaking, the pool needs to be shutdown() when exiting, and the monitoring socket must also be shut down. But with hundreds of lines of code, there is no need to force it. With ctrl + c, it Let the operating system reclaim resources.

Why is PHP not good at network programming? First of all, I used the stream_socket_XXX related functions. Why not use socket extension? Because there is a problem with the socket extension, see: https://github.com/krakjoe/pthreads/issues/581 And stream_set_timeout does not work for advanced operations such as stream_socket_recvfrom, see: http://php.net/manual/en /function.stream-set-timeout.phpAnd these need to be considered when writing a proxy. For example, when connecting to a remote target server, there is no timeout control, and the thread pool can easily become full.

For testing, just use curl. By the way, currently only remote dns resolution is supported. Why? Because this toy will need to be used to access the Internet later: curl --socks5-hostname 127.0.0.1:1080http://ip.cn

Class Pipe extends Threaded
{
  private $client;
  private $remote;
  public function __construct($client, $remote) 
  {
    $this->client = $client;
    $this->remote = $remote; 
  }
  public function run()
  {
    for ( ; ; ) {
        $data = stream_socket_recvfrom($this->client, 4096);
        if ($data === false || strlen($data) === 0) {
          break;
        } 
        $sendBytes = stream_socket_sendto($this->remote, $data);
        if ($sendBytes <= 0) {
          break;
        }
    }
    stream_socket_shutdown($this->client, STREAM_SHUT_RD);
    stream_socket_shutdown($this->remote, STREAM_SHUT_WR);
  }
}

Class Client extends Threaded
{
  public $fd;
  public function __construct($fd)
  {
    $this->fd = $fd; 
  }

  public function run()
  {
    $data = stream_socket_recvfrom($this->fd, 2);
    $data = unpack('c*', $data);
    if ($data[1] !== 0x05) {
      stream_socket_shutdown($this->fd, STREAM_SHUT_RDWR);
      echo '协议不正确.', PHP_EOL;
      return;
    }
    $nmethods = $data[2];
    $data = stream_socket_recvfrom($this->fd, $nmethods);
    stream_socket_sendto($this->fd, "\x05\x00");
    $data = stream_socket_recvfrom($this->fd, 4);
    $data = unpack('c*', $data);
    $addressType = $data[4];
    if ($addressType === 0x03) { // domain
      $domainLength = unpack('c', stream_socket_recvfrom($this->fd, 1))[1];
      $data = stream_socket_recvfrom($this->fd, $domainLength + 2);
      $domain = substr($data, 0, $domainLength);
      $port = unpack("n", substr($data, -2))[1];
    } else {
      stream_socket_shutdown($this->fd, STREAM_SHUT_RDWR);
      echo '请使用远程dns解析.', PHP_EOL;
    }

    stream_socket_sendto($this->fd, "\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00");
    echo "{$domain}:{$port}", PHP_EOL;
    $remote = stream_socket_client("tcp://{$domain}:{$port}");
    if ($remote === false) {
      stream_socket_shutdown($this->fd, STREAM_SHUT_RDWR);
      return;
    }

    $pool = $this->worker->pipePool;

    $pipe1 = new Pipe($remote, $this->fd);
    $pipe2 = new Pipe($this->fd, $remote);

    $pool->submit($pipe1);
    $pool->submit($pipe2);
  }
}

class ProxyWorker extends Worker
{
  public $pipePool;
  public function __construct($pipePool)
  {
    $this->pipePool = $pipePool;
  }
}

$server = stream_socket_server('tcp://0.0.0.0:1080', $errno, $errstr);
if ($server === false)
  exit($errstr);

$pipePool = new Pool(200, Worker::class);
$pool = new Pool(50, 'ProxyWorker', [$pipePool]);

for( ; ; ) {
  $fd = @stream_socket_accept($server, 60);
  if ($fd === false)
    continue;
  $pool->submit(new Client($fd));
}
Copy after login

The above introduces 100 lines of PHP code to implement socks5 proxy server, including all aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Python's socket and socketserver How to use Python's socket and socketserver May 28, 2023 pm 08:10 PM

1. Socket programming based on TCP protocol 1. The socket workflow starts with the server side. The server first initializes the Socket, then binds to the port, listens to the port, calls accept to block, and waits for the client to connect. At this time, if a client initializes a Socket and then connects to the server (connect), if the connection is successful, the connection between the client and the server is established. The client sends a data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, and finally closes the connection. An interaction ends. Use the following Python code to implement it: importso

IO multiplexing of PHP+Socket series and implementation of web server IO multiplexing of PHP+Socket series and implementation of web server Feb 02, 2023 pm 01:43 PM

This article brings you relevant knowledge about php+socket, which mainly introduces IO multiplexing and how php+socket implements web server? Friends who are interested can take a look below. I hope it will be helpful to everyone.

How to use Spring Boot+Vue to implement Socket notification push How to use Spring Boot+Vue to implement Socket notification push May 27, 2023 am 08:47 AM

The first step on the SpringBoot side is to introduce dependencies. First we need to introduce the dependencies required for WebSocket, as well as the dependencies for processing the output format com.alibabafastjson1.2.73org.springframework.bootspring-boot-starter-websocket. The second step is to create the WebSocket configuration class importorg. springframework.context.annotation.Bean;importorg.springframework.context.annotation.Config

How to debug Java Stream operations in IntelliJ IDEA How to debug Java Stream operations in IntelliJ IDEA May 09, 2023 am 11:25 AM

Stream operation is a highlight of Java8! Although java.util.stream is very powerful, there are still many developers who rarely use it in actual work. One of the most complained reasons is that it is difficult to debug. This was indeed the case at the beginning, because streaming operations such as stream cannot be used in DEBUG When it is one line of code, when it comes to the next step, many operations are actually passed at once, so it is difficult for us to judge which line in it is the problem. Plug-in: JavaStreamDebugger If the IDEA version you are using is relatively new, this plug-in is already included and does not need to be installed. If it is not installed yet, install it manually and then continue below.

Research on real-time file transfer technology using PHP and Socket Research on real-time file transfer technology using PHP and Socket Jun 28, 2023 am 09:11 AM

With the development of the Internet, file transfer has become an indispensable part of people's daily work and entertainment. However, traditional file transfer methods such as email attachments or file sharing websites have certain limitations and cannot meet the needs of real-time and security. Therefore, using PHP and Socket technology to achieve real-time file transfer has become a new solution. This article will introduce the technical principles, advantages and application scenarios of using PHP and Socket technology to achieve real-time file transfer, and demonstrate the implementation method of this technology through specific cases. technology

Common network communication and security problems and solutions in C# Common network communication and security problems and solutions in C# Oct 09, 2023 pm 09:21 PM

Common network communication and security problems and solutions in C# In today's Internet era, network communication has become an indispensable part of software development. In C#, we usually encounter some network communication problems, such as data transmission security, network connection stability, etc. This article will discuss in detail common network communication and security issues in C# and provide corresponding solutions and code examples. 1. Network communication problems Network connection interruption: During the network communication process, the network connection may be interrupted, which may cause

PHP+Socket series realizes data transmission between client and server PHP+Socket series realizes data transmission between client and server Feb 02, 2023 am 11:35 AM

This article brings you relevant knowledge about php+socket. It mainly introduces what is socket? How does php+socket realize client-server data transmission? Friends who are interested can take a look below. I hope it will be helpful to everyone.

How to get max value from stream in java8 How to get max value from stream in java8 May 14, 2023 pm 03:43 PM

java8's stream takes maxpublicstaticvoidmain(String[]args){Listlist=Arrays.asList(1,2,3,4,5,6);Integermax=list.stream().max((a,b)->{if (a>b){return1;}elsereturn-1;}).get();System.out.println(max);}Note: The size is determined here through positive and negative numbers and 0 values. Instead of writing it directly if(a>b){returna;}elseretur

See all articles