Tencent Cloud EdgeOne

Tencent Cloud EdgeOne
L4 Proxy
Product Documentation©2013-2022 Tencent Cloud. All rights reserved.

Page 1 of 77

Tencent Cloud EdgeOne

Copyright Notice©2013-2024 Tencent Cloud. All rights reserved.
Copyright in this document is exclusively owned by Tencent Cloud. You must not reproduce, modify, copy or distributein any way, in whole or in part, the contents of this document without Tencent Cloud's the prior written consent.
Trademark Notice

All trademarks associated with Tencent Cloud and its services are owned by Tencent Cloud Computing (Beijing)
Company Limited and its affiliated companies. Trademarks of third parties referred to in this document are owned bytheir respective proprietors.
Service Statement
This document is intended to provide users with general information about Tencent Cloud's products and services
only and does not form part of Tencent Cloud's terms and conditions. Tencent Cloud's products or services are
subject to change. Specific products and services and the standards applicable to them are exclusively provided for in
Tencent Cloud's applicable terms and conditions.

©2013-2022 Tencent Cloud. All rights reserved.

Page 2 of 77

Tencent Cloud EdgeOne

Contents
L4 Proxy
Overview
Creating an L4 Proxy Instance
Modifying an L4 Proxy Instance
Disabling or Deleting an L4 Proxy InstanceBatch Configuring Forwarding Rules
Obtaining Real Client IPs
Obtaining Real TCP Client IPs via TOA
Obtaining Real Client IPs Through Protocol V1/V2
Overview
Method 1: Obtaining Real Client IPs Through Nginx
Method 2: Parsing Real Client IPs on Application Server
Format of Real Client IPs Obtained Through Proxy Protocol V1/V2
Transmitting Client Real IP via SPP Protocol©2013-2022 Tencent Cloud. All rights reserved.

Page 3 of 77

Tencent Cloud EdgeOne

L4 Proxy
Overview：

Last updated 2024-06-19 17:30:23

How It Works
L4 proxy is the acceleration service of EdgeOne based on TCP/UDP. By leveraging widely distributed layer-4 proxynodes, unique DDoS module, and smart routing technology, EdgeOne implements nearby access for end users, edge
traffic cleansing, and port monitoring and forwarding. It thus offers high-availability and low-latency DDoS mitigation
and acceleration services for layer-4 applications.

Use Cases
Game Acceleration
L4 proxy accelerates data transmission over TCP/UDP for mobile and PC games, such as real-time battle games and
MMORPGs that require global access to a unified server. L4 proxy connects players to the nearest high-speed
channels to reduce the packet loss rate and latency of the game due to varying network conditions across regions.

©2013-2022 Tencent Cloud. All rights reserved.

Page 4 of 77

Tencent Cloud EdgeOne

OA Application Acceleration
Generally, in cross-regional OA scenarios, the business data of a company is stored in the master data center at its
headquarters. This often results in a high packet loss rate with high latency during cross-regional communication due
to network issues, causing troubles in cross-regional business access and data synchronization. L4 proxy effectively
solves those network issues and improves the business access experience by connecting users to the nearest
EdgeOne nodes and optimizing the access links.

©2013-2022 Tencent Cloud. All rights reserved.

Page 5 of 77

Tencent Cloud EdgeOne

Real-time Audio/Video
L4 proxy supports forwarding acceleration over UDP. This ensures reliable audio and video transmission in real-time
interactive scenarios, such as video meetings and video communication between anchors and audience members. L4proxy solves network issues such as audio/video lags, packet loss, and high latency during cross-ISP, long distance,and cross-border communication.

Instance Quotas©2013-2022 Tencent Cloud. All rights reserved.

Page 6 of 77

Tencent Cloud EdgeOne

By default, L4 proxy provides one instance in CNAME access mode. To connect through an anycast IP address or
add more CNAME instances, go to the L4 Proxy page and click Adjust quota. For more information about the pricing
of instances, see L4 proxy instance.

©2013-2022 Tencent Cloud. All rights reserved.

Page 7 of 77

Tencent Cloud EdgeOne

Creating an L4 Proxy Instance：

Last updated 2024-08-01 21:32:16

Use Cases
This document describes how to create and configure an L4 proxy instance.

Directions
1. Log in to the EdgeOne console and click Site List in the left sidebar. In the site list, click the target site.
2. On the site details page, click L4 proxy.
3. On the page that appears, click Create L4 proxy instance.

4. Specify parameters on the Service Configurations page. By default, the service region is the accelerated regionof the current site. The table below lists the parameters:©2013-2022 Tencent Cloud. All rights reserved.

Page 8 of 77

Tencent Cloud EdgeOne

Item

Description

Instance name

The name must be 1 to 200 characters in length and can contain uppercase andlowercase letters, digits, underscores (_), and hyphens (-).

Security

Default protection: Enabled by default, for details, please refer to DDoS Protection
Overview.

Configuration

Exclusive DDoS Protection: For details, please refer to the usage of Exclusive DDoS
Protection.

Fixed IP

When enabled, users can access through a fixed IP address.

IPv6 access

If you enable this feature, EdgeOne nodes can be accessed over the IPv6 protocol.

Chinese MLCborder

When enabled, it will optimize the access performance for Chinese mainland users. For

acceleration

details, please refer to Cross-Regional Secure Acceleration (Overseas Sites).

Note:
Fixed IP, IPv6 access, and Chinese MLC- border acceleration cannot be enabled at the same time, and there is a
conflicting relationship between security protection configuration and access configuration in different acceleration
regions. The conflicts are as follows:
Security
Protection
Configuration

FeatureGlobal (MLC Excluded)

Mainland China

GlobalPlatform default

Fixed IP✓✕✕

IPv6 access

✓

✓

✓

protection©2013-2022 Tencent Cloud. All rights reserved.

Page 9 of 77

Tencent Cloud EdgeOne

Chinese MLC-

✓

✕

✕

Fixed IP✓✕✕

IPv6 access

✓

✕

✕

Chinese MLCborder acceleration

✓

✕

✕

border acceleration

Exclusive DDoS
protection

5. View subscription fees, check and agree to the EdgeOne Service Level Agreement and Refund Policy below, andclick Subscribe. For billing description, please refer to the Billing overview.
6. Specify the forwarding rules. On the L4 proxy page, select the newly created L4 proxy instance, click Configuration,enter the instance details page to configure forwarding rules.You can also import multiple forwarding rules at a time.
For more information, see Batch Configuring Forwarding Rules. The table below lists the fields of a forwarding rule:

Note:
1. If you specify Origin group for Origin type, you can specify only self-owned origins. In this case, a COS
bucket is not supported as the origin.
2. You can specify at most 2,000 forwarding rules for each L4 proxy instance.
Item

Description

Rule ID

Auto-generated, not supported for modification, unique identifier of the rule.

Forwarding protocol

Forwarding protocol of L4 proxy. Valid values: TCP and UDP.
The supported port number ranges from 1 to 64999. You can enter multiple ports

Forwarding port

separated with semicolons (;) or use a hyphen to enter a port range. You can enter up
to 20 ports in a forwarding rule.
The following ports are reserved for internal use, please do not use them:
For TCP forwarding protocol: 3943, 3944, 6088, 36000, 56000.
For UDP forwarding protocol: 4789, 4790, 6080, 61708.
Single origin: If you specify Single origin for Origin type, you can enter the IP

Origin type andaddress or domain name of a single origin.

Origin address

Origin group: If you specify Origin group for Origin type, you can select an
origin from an existing origin group, or create an origin group.

©2013-2022 Tencent Cloud. All rights reserved.

Page 10 of 77

Tencent Cloud EdgeOne

Origin port

You can enter a single port or a port range. If it is a port range, the forwarding port mustalso be a port range, and the length of the origin port and forwarding port ranges must
be consistent.
For example: If the forwarding port range is 80-90 , the origin port range can be
80-90 or 90-100 .

Session persistence

As long as an origin server IP remains unchanged, traffic from the same client IP will
always be forwarded to the same origin server IP.
TOA: Pass client IPs via TCP Option (type 200), which only supports TCP protocols.
Proxy Protocol V1 (recommended): Pass client IPs as plaintext by using the TCP

Pass client IP

Rule Tagheader, which only supports TCP protocols.
Proxy Protocol V2: Pass client IPs by using the header. V2 uses the binary format andsupports both TCP and UDP protocols. The first packet of each TCP connection carriesa PPv2 header., while only the first data packet carries the header for UDP.
Not passed: Real client IPs will not be transferred.
Optional, you can enter 1-50 any characters to identify the forwarding rule.

7. Click Save to complete the configuration of the L4 proxy rules.

©2013-2022 Tencent Cloud. All rights reserved.

Page 11 of 77

Tencent Cloud EdgeOne

Modifying an L4 Proxy Instance：

Last updated 2023-09-11 17:25:53

Use Cases
This document describes how to modify the configuration of an L4 proxy instance.
Note:
After an L4 proxy instance is created, you cannot modify its scheduling mode or proxy mode. To do so, you can delete
the instance and create a new one.
You can disable and then delete a forwarding rule.

Directions
1. Log in to the EdgeOne console and click Site List in the left sidebar. In the site list, click the target site.
2. On the site details page, click L4 proxy.
3. On the page that appears, find the target L4 proxy instance and click configure in the Operation column.
4. On the page that appears, you can enable or disable IPv6 access and modify Chinese MLC- border acceleration.
You can also add, edit, enable/disable, or delete a forwarding rules.

©2013-2022 Tencent Cloud. All rights reserved.

Page 12 of 77

Tencent Cloud EdgeOne©2013-2022 Tencent Cloud. All rights reserved.

Page 13 of 77

Tencent Cloud EdgeOne

Disabling or Deleting an L4 Proxy Instance：

Last updated 2023-09-11 17:37:36

Use Cases
This document describes how to disable or delete an L4 proxy instance.
Note:
To delete an L4 proxy instance, you must disable it first, which usually takes a few minutes.

Directions
1. Log in to the EdgeOne console and click Site List in the left sidebar. In the site list, click the target site.
2. On the site details page, click L4 proxy.
3. On the page that appears, find the target L4 proxy instance and click Disable in the Operation column.

4. Click Delete as needed.

©2013-2022 Tencent Cloud. All rights reserved.

Page 14 of 77

Tencent Cloud EdgeOne

Batch Configuring Forwarding Rules：

Last updated 2023-09-11 17:38:37

Use Cases
Tencent Cloud EdgeOne allows you to configure multiple forwarding rules for an L4 proxy instance. This document
describes how to import and export multiple forwarding rules at a time.
Note:
1. You can import up to 2,000 forwarding rules at a time. Each L4 proxy instance supports up to 2,000 forwarding
rules.
2. The fields in batch imported forwarding rules are not case-sensitive.
3. The imported forwarding rules cannot use the forwarding ports of existing forwarding rules.

Directions
Importing multiple forwarding rules at a time
1. Log in to the EdgeOne console and click Site List in the left sidebar. In the site list, click the target site.
2. On the site details page, click L4 proxy.
3. On the page that appears, find the target L4 proxy instance and click View in the Operation column.
4. On the page that appears, click Batch import.

5. In the pop-up window, enter the forwarding rules to be imported. You must enter one rule per row and specify theforwarding protocol, forwarding port, origin address, origin port, session persistence status, and IP passing mode.
Separate fields with spaces. Example: tcp:123 test.origin.com 456 on ppv1 .

©2013-2022 Tencent Cloud. All rights reserved.

Page 15 of 77

Tencent Cloud EdgeOne

The table below lists the fields of a forwarding rule:
Field

Description
The supported forwarding protocols are TCP and UDP.
The supported port number ranges from 1 to 64999,. You can enter multiple ports

Forwarding
protocol:Forwarding
port

separated with semicolons (;) or use a hyphen to enter a port range. You can enter up to
20 ports in a forwarding rule.
The following ports are reserved for internal use, please do not use them:
For TCP forwarding protocol: 3943, 3944, 6088, 36000, 56000.
For UDP forwarding protocol: 4789, 4790, 6080, 61708.
If you specify Single origin for Origin type, you can enter the IP address orOrigin address

domain name of a single origin.
If you specify Origin group for Origin type, you can enter the name of an existingorigin group in the format of og:{OriginGroupName} . Example:
og:testorigin .

Origin port

You can enter a single port or a port range. If it is a port range, the forwarding port mustalso be a port range, and the length of the origin port and forwarding port ranges must be
consistent.

©2013-2022 Tencent Cloud. All rights reserved.

Page 16 of 77

Tencent Cloud EdgeOne

For example: If the forwarding port range is 80-90 , the origin port range can be 8090 or 90-100 .
Session persistence

Valid values: on and off.

Pass client IP

Valid values: toa, ppv1, ppv2, and off.

Rule Tag

Optional, you can enter 1-50 any characters to identify the forwarding rule.

6. Click OK.

Exporting multiple forwarding rules at a time
1. Log in to the EdgeOne console and click Site List in the left sidebar. In the site list, click the target site.
2. On the site details page, click L4 proxy.
3. On the page that appears, find the target L4 proxy instance and click View in the Operation column.
4. On the page that appears, click Batch export.

5. In the pop-up window, click OK to export all forwarding rules to a .txt file. The format of the exported rules is thesame as that of the imported rules.

©2013-2022 Tencent Cloud. All rights reserved.

Page 17 of 77

Tencent Cloud EdgeOne

Obtaining Real Client IPs
Obtaining Real TCP Client IPs via TOA：

Last updated 2023-09-11 17:40:22
You can use this document to learn how to get the TCP client IP via TOA when using L4 proxy.

Use Cases
Using L4 acceleration for data packets will have the source IP and port modified, so the origin does not get the original
information. To enable the origin to get the real client IP and port, you can pass the information using TOA whencreating an acceleration channel. In this way, the real client IP and port are passed into the TCP option field.
Meanwhile, you need to install TOA on the origin to get that information.

Directions
Step 1: Pass the client IP via TOA
To get the TCP client IP via TOA, set Pass client IP to TOA in L4 proxy forwarding rules in the console. For details
on how to modify rules, see: Modifying an L4 Proxy Instance.

Step 2: Load TOA on backend server
You can load the TOA module using either of the following methods:
Method 1 (recommended): Based on the Linux version the origin uses, download the complied toa.ko file and load it
directly.
Method 2: If you cannot find the appropriate Linux version, download the TOA source code file and compile and load it
yourself.

：

Note©2013-2022 Tencent Cloud. All rights reserved.

Page 18 of 77

Tencent Cloud EdgeOne

Due to the differences in installation environments, if you encounter issues during the loading process using Method 1,
please try Method 2 and install the compilation environment manually.
Method 1: Download and load the compiled TOA module
Method 2: Compile and load the TOA module
1. Download and decompress the TOA package corresponding to the version of Linux OS on Tencent Cloud.
centosCentOS-7.2-x86_64.tar.gz
CentOS-7.3-x86_64.tar.gz
CentOS-7.4-x86_64.tar.gz
CentOS-7.5-x86_64.tar.gz
CentOS-7.6-x86_64.tar.gz
CentOS-7.7-x86_64.tar.gz
CentOS-7.8-x86_64.tar.gz
CentOS-7.9-x86_64.tar.gz
CentOS-8.0-x86_64.tar.gz
CentOS-8.2-x86_64.tar.gz
debian
Debian-11.1-x86_64.tar.gz
Debian-10.2-x86_64.tar.gz
Debian-9.0-x86_64.tar.gz
suse linux
openSUSE-Leap-15.3-x86_64.tar.gz
ubuntuUbuntu-14.04.1-LTS-x86_64.tar.gz
Ubuntu-16.04.1-LTS-x86_64.tar.gz
Ubuntu-18.04.1-LTS-x86_64.tar.gz
Ubuntu-20.04.1-LTS-x86_64.tar.gz
2. After decompression is complete, run the cd command to access the decompressed folder. Then load themodule as follows:
Load TOA with a script
Manually load TOA©2013-2022 Tencent Cloud. All rights reserved.

Page 19 of 77

Tencent Cloud EdgeOne/bin/bash -c "$(curl -fsSL https://edgeone-document-file-1258344699.cos.ap-guangzho
When it is loaded successfully, you will see the following information:©2013-2022 Tencent Cloud. All rights reserved.

Page 20 of 77

Tencent Cloud EdgeOne# Decompress the tar package.
tar -zxvf CentOS-7.2-x86_64.tar.gz# Enter the directory of the decompressed package.
cd CentOS-7.2-x86_64# Load the TOA module.
insmod toa.ko# Copy the TOA module to the kernel module directory.
cp toa.ko /lib/modules/`uname -r`/kernel/net/netfilter/ipvs/toa.ko# Configure the TOA module to load automatically at system startup.
echo "insmod /lib/modules/`uname -r`/kernel/net/netfilter/ipvs/toa.ko" >> /etc/rc.l©2013-2022 Tencent Cloud. All rights reserved.

Page 21 of 77

Tencent Cloud EdgeOne

Run the following command to check whether the loading is successful:

lsmod | grep toa
If you see "TOA" in the message, the module is loaded successfully:©2013-2022 Tencent Cloud. All rights reserved.

Page 22 of 77

Tencent Cloud EdgeOne

1. Install the compilation environment.
1.1 Make sure kernel-devel and kernel-headers are installed and consistent with the kernel version.
1.2 Make sure the gcc and make dependencies are installed.
1.3 If these environmental dependencies are not installed, run the installation command:
CentOS
Ubuntu/Debian©2013-2022 Tencent Cloud. All rights reserved.

Page 23 of 77

Tencent Cloud EdgeOne

yum install -y gcc
yum install -y makeyum install -y kernel-headers kernel-devel©2013-2022 Tencent Cloud. All rights reserved.

Page 24 of 77

Tencent Cloud EdgeOne

apt-get install -y gcc
apt-get install -y makeapt-get install -y linux-headers-$(uname -r)

2. After the compilation environment is installed, download, compile and load the source code.
Compile and load TOA with a script
Manually compile and load TOA©2013-2022 Tencent Cloud. All rights reserved.

Page 25 of 77

Tencent Cloud EdgeOne/bin/bash -c "$(curl -fsSL https://edgeone-document-file-1258344699.cos.ap-guangzho©2013-2022 Tencent Cloud. All rights reserved.

Page 26 of 77

Tencent Cloud EdgeOne# Create a compilation directory and enter it.
mkdir toa_compile && cd toa_compile# Download the source code (tar.gz)
curl -o toa.tar.gz https://edgeone-document-file-1258344699.cos.ap-guangzhou.myqclo# Decompress the tar package
tar -zxvf toa.tar.gz# Compile the toa.ko file. After the compilation is successful, the file will be ge
make# Load the TOA module.
insmod toa.ko# Copy the TOA module to the kernel module directory.

©2013-2022 Tencent Cloud. All rights reserved.

Page 27 of 77

Tencent Cloud EdgeOne

cp toa.ko /lib/modules/`uname -r`/kernel/net/netfilter/ipvs/toa.ko# Configure the TOA module to load automatically at system startup
echo "insmod /lib/modules/`uname -r`/kernel/net/netfilter/ipvs/toa.ko" >> /etc/rc.l
3. Run the following command to check whether the loading is successful:

lsmod | grep toa
If you see "TOA" in the message, the module is loaded successfully:©2013-2022 Tencent Cloud. All rights reserved.

Page 28 of 77

Tencent Cloud EdgeOne

Step 3: Verify the configuration
You can verify the configuration by building a TCP server to receive client requests from another server. See thesample:1. On the current server, create an HTTP server in Python to act as a TCP server:# Use python2
python2 -m SimpleHTTPServer 10000©2013-2022 Tencent Cloud. All rights reserved.

Page 29 of 77

Tencent Cloud EdgeOne# Use python3
python3 -m http.server 10000
2. Make another server work as a client to send requests:# Use curl to initiate an HTTP request, where the hostname and forwarding port of t
curl -i "http://a8b7f59fc8d7e6c9.example.com.edgeonedy1.com:10000/"
3. If TOA is loaded, the real client address can be seen on the server:©2013-2022 Tencent Cloud. All rights reserved.

Page 30 of 77

Tencent Cloud EdgeOne

You can also get either the IPv4 or IPv6 address of the client by following the steps above.
For origin IPv4 addresses, get the client IPv4 address.
For origin IPv6 addresses, get the client IPv6 address.
If you need to get both IPv4 and IPv6 addresses, modify the origin's business code while loading the TOA module as
instructed here.

Getting Both IPv4 and IPv6 Addresses
Note:This section provide guidance on how to get both IPv4 and IPv6 addresses by modifying the business code of theorigin.
The origin can listen on requests in either of the following methods:
1. Use the structure struct sockaddr_in to listen on IPv4 addresses.
2. Use the structure struct sockaddr_in6 to listen on IPv6 addresses.

Sample code
Listen on IPv4 addresses
Listen on IPv6 addresses

CJava©2013-2022 Tencent Cloud. All rights reserved.

Page 31 of 77

Tencent Cloud EdgeOne#include <sys/socket.h>#include <stdio.h>#include <unistd.h>#include <netinet/in.h>#include <memory.h>#include <arpa/inet.h>
int main(int argc, char** argv) {int
l_sockfd;// The server address is an IPv4 address.
struct sockaddr_in serveraddr;©2013-2022 Tencent Cloud. All rights reserved.

Page 32 of 77

Tencent Cloud EdgeOne// In this case, the client address must adopt the IPv6 structure.
struct sockaddr_in6 clientAddr;
int server_port = 10000;
memset(&serveraddr, 0, sizeof(serveraddr));// Create a socket.
l_sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (l_sockfd == -1){
printf("Failed to create socket.\\n");return -1;}// Initialize the server.
memset(&serveraddr, 0, sizeof(struct sockaddr_in));serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(server_port);
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
int isReuse = 1;
setsockopt(l_sockfd, SOL_SOCKET,SO_REUSEADDR,(const char*)&isReuse,sizeof(i// Associate the socket and server address.
int nRet = bind(l_sockfd,(struct sockaddr*)&serveraddr, sizeof(serveraddr))
if(-1 == nRet){
printf("bind error\\n");return -1;}// Listen on the socket.
listen(l_sockfd, 5);
int clientAddrLen = sizeof(clientAddr);
memset(&clientAddr, 0, sizeof(clientAddr));// Accept connections from the client.
int linkFd = accept(l_sockfd, (struct sockaddr*)&clientAddr, &clientAddrLen);
if(-1 == linkFd){
printf("accept error\\n");return -1;}// Modifications to make: Decide whether the client is an IPv4 or IPv6 address//
AF_INET indicates that the client adopts IPv4. In this case, convert the//
AF_INET6 indicates that the client adopts IPv6. In this case, use struct
if (clientAddr.sin6_family == AF_INET) {printf("AF_INET accept getpeername %s : %d successful\\n",inet_ntoa(((struct sockaddr_in*)&clientAddr)->sin_addr),
ntohs(((struct sockaddr_in*)&clientAddr)->sin_port));©2013-2022 Tencent Cloud. All rights reserved.

Page 33 of 77

Tencent Cloud EdgeOne}else if (clientAddr.sin6_family == AF_INET6){char addr_p[128] = {0};inet_ntop(AF_INET6, (void *)&((struct sockaddr_in6*)&clientAddr)->sin6_addr
printf("AF_INET6 accept getpeername %s : %d successful\\n",addr_p,ntohs(((struct sockaddr_in6*)&clientAddr)->sin6_port));}else{
printf("unknow sin_family:%d \\n", clientAddr.sin6_family);}close(l_sockfd);
return 0;}©2013-2022 Tencent Cloud. All rights reserved.

Page 34 of 77

Tencent Cloud EdgeOne

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class ServerDemo {©2013-2022 Tencent Cloud. All rights reserved.

Page 35 of 77

Tencent Cloud EdgeOne/** If using the IPv4 address structure to build the service, use IPV4_HOST */public static final String IPV4_HOST = "0.0.0.0";/** If using the IPv6 address structure to build the service, use IPV6_HOST */public static final String IPV6_HOST = "::";

public static void main(String[] args) {int serverPort = 10000;
try (ServerSocket serverSocket = new ServerSocket()) {// Setting address reuseserverSocket.setReuseAddress(true);// Bound server address and port, using IPv4 here
serverSocket.bind(new InetSocketAddress(InetAddress.getByName(IPV4_HOST
System.out.println("Server is listening on port " + serverPort);

while (true) {// Accepting Client connections
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket.getRemot// Processing Client requests
handleClientRequest(clientSocket);}} catch (IOException e) {System.err.println("Failed to create server socket: " + e.getMessage())}}/*** Processing Function, site business implement, here is just an example* The purpose of this Function is to Return the Client's input verbatim to the*/private static void handleClientRequest(Socket clientSocket) {try (InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream()) {// Reading the Data received from the Client
byte[] buffer = new byte[1024];
int bytesRead;©2013-2022 Tencent Cloud. All rights reserved.

Page 36 of 77

Tencent Cloud EdgeOne

while ((bytesRead = inputStream.read(buffer)) != -1) {// Reply the received Data to the Client as it isoutputStream.write(buffer, 0, bytesRead);}} catch (IOException e) {// When the Client disconnects
System.err.println("Failed to handle client request: " + e.getMessage()} finally {try {clientSocket.close();} catch (IOException e) {System.err.println("Failed to close client socket: " + e.getMessage
}
}
}
}

C
Java

©2013-2022 Tencent Cloud. All rights reserved.

Page 37 of 77

Tencent Cloud EdgeOne#include <sys/socket.h>#include <stdio.h>#include <unistd.h>#include <netinet/in.h>#include <memory.h>#include <arpa/inet.h>
int main(int argc, char **argv){
int
l_sockfd;// The server address is an IPv6 address.

©2013-2022 Tencent Cloud. All rights reserved.

Page 38 of 77

Tencent Cloud EdgeOne

struct sockaddr_in6 serveraddr;// The client address is an IPv6 address.
struct sockaddr_in6 clientAddr;
int server_port = 10000;
memset(&serveraddr, 0, sizeof(serveraddr));// Create a socket.
l_sockfd = socket(AF_INET6, SOCK_STREAM, 0);
if (l_sockfd == -1){
printf("Failed to create socket.\\n");return -1;}// Set the server address.
memset(&serveraddr, 0, sizeof(struct sockaddr_in6));serveraddr.sin6_family = AF_INET6;
serveraddr.sin6_port = htons(server_port);
serveraddr.sin6_addr = in6addr_any;
int isReuse = 1;
setsockopt(l_sockfd, SOL_SOCKET,SO_REUSEADDR,(const char*)&isReuse,sizeof(i// Associate the socket and server address.
int nRet = bind(l_sockfd,(struct sockaddr*)&serveraddr, sizeof(serveraddr))
if(-1 == nRet){
printf("bind error\\n");return -1;}// Listen on the socket.
listen(l_sockfd, 5);
int clientAddrLen = sizeof(clientAddr);
memset(&clientAddr, 0, sizeof(clientAddr));// Accept connection requests from the client.
int linkFd = accept(l_sockfd, (struct sockaddr*)&clientAddr, &clientAddrLen);
if(-1 == linkFd){
printf("accept error\\n");return -1;}// The client addresses received here are all stored in the IPv6 structure.
// The IPv4 addresses are mapped to IPv6 addresses, for example, "::ffff:119.29
char addr_p[128] = {0};inet_ntop(AF_INET6, (void *)&clientAddr.sin6_addr, addr_p, (socklen_t )sizeof(aprintf("accept %s : %d successful\\n", addr_p, ntohs(clientAddr.sin6_port));©2013-2022 Tencent Cloud. All rights reserved.

Page 39 of 77

Tencent Cloud EdgeOne// Modifications to make: Use the macro definition IN6_IS_ADDR_V4MAPPED to deciif(IN6_IS_ADDR_V4MAPPED(&clientAddr.sin6_addr)) {struct sockaddr_in real_v4_sin;
memset (&real_v4_sin, 0, sizeof (struct sockaddr_in));
real_v4_sin.sin_family = AF_INET;
real_v4_sin.sin_port = clientAddr.sin6_port;// The last four bytes represent the IPv4 address of the client.
memcpy (&real_v4_sin.sin_addr, ((char *)&clientAddr.sin6_addr) + 12, 4);printf("connect %s successful\\n", inet_ntoa(real_v4_sin.sin_addr));}close(l_sockfd);
return 0;}©2013-2022 Tencent Cloud. All rights reserved.

Page 40 of 77

Tencent Cloud EdgeOne

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
public class ServerDemo {©2013-2022 Tencent Cloud. All rights reserved.

Page 41 of 77

Tencent Cloud EdgeOne/** If using the IPv4 address structure to build the service, use IPV4_HOST */public static final String IPV4_HOST = "0.0.0.0";/** If using the IPv6 address structure to build the service, use IPV6_HOST */public static final String IPV6_HOST = "::";
public static void main(String[] args) {int serverPort = 10000;
try (ServerSocket serverSocket = new ServerSocket()) {// Setting address reuseserverSocket.setReuseAddress(true);// Bound server address and port, using IPv4 here
serverSocket.bind(new InetSocketAddress(InetAddress.getByName(IPV6_HOST
System.out.println("Server is listening on port " + serverPort);
while (true) {// Accepting Client connections
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket.getRemot// Processing Client requests
handleClientRequest(clientSocket);}} catch (IOException e) {System.err.println("Failed to create server socket: " + e.getMessage())}}/*** Processing Function, site business implement, here is just an example* The purpose of this Function is to Return the Client's input verbatim to the*/private static void handleClientRequest(Socket clientSocket) {try (InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream()) {// Reading the Data received from the Client
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {// Reply the received Data to the Client as it isoutputStream.write(buffer, 0, bytesRead);}} catch (IOException e) {// When the Client disconnects
System.err.println("Failed to handle client request: " + e.getMessage()©2013-2022 Tencent Cloud. All rights reserved.

Page 42 of 77

Tencent Cloud EdgeOne} finally {try {clientSocket.close();} catch (IOException e) {System.err.println("Failed to close client socket: " + e.getMessage}}}}

console output result©2013-2022 Tencent Cloud. All rights reserved.

Page 43 of 77

Tencent Cloud EdgeOne

Server is listening on port 10000
New client connected: /127.0.0.1:50680
New client connected: /0:0:0:0:0:0:0:1:51124
New client connected: /127.0.0.1:51136

References
Monitoring TOA Running Status©2013-2022 Tencent Cloud. All rights reserved.

Page 44 of 77

Tencent Cloud EdgeOne

To ensure execution stability, this kernel module allows you to monitor status. After inserting the toa.ko kernel
module, you can monitor the TOA working status in either of the following ways.

cat /proc/net/toa_stats
This figure shows the TOA running status:©2013-2022 Tencent Cloud. All rights reserved.

Page 45 of 77

Tencent Cloud EdgeOne

The monitoring metrics are described as follows:
MetricDescription

syn_recv_sock_toa

Receives connections with TOA information.

syn_recv_sock_no_toa

Receives connections without TOA information.

getname_toa_ok

This count increases when you call getsockopt and obtain the source IP
address successfully or when you call accept to receive client requests.
This count increases when you call getsockopt and obtain a source IP

getname_toa_mismatch

getname_toa_empty

address that does not match the required type. For example, if a client connection
contains a source IPv4 address whereas you obtain an IPv6 address, the countwill increase.
This count increases when the getsockopt function is called in a client filedescriptor that does not contain TOA.

ip6_address_alloc
audio/video proxy

Allocates space to store the information when TOA obtains the source IP addressand source port saved in the TCP data packet.

ip6_address_free
audio/video proxy

When the connection is released, TOA will release the memory previously used tosave the source IP and source port. If all connections are closed, the total count of
ip6_address_alloc for each CPU should be equal to the count of thismetric.

©2013-2022 Tencent Cloud. All rights reserved.

Page 46 of 77

Tencent Cloud EdgeOne

Obtaining Real Client IPs Through Protocol
V1/V2
Overview：

Last updated 2023-06-29 15:37:55
This document describes how to obtain real client IPs through Proxy Protocol V1/V2 when you enable the L4 proxyacceleration.

Scenarios
When the datagrams are accelerated through L4 acceleration connection, you can pass the real client IPs and Ports tothe origin server through Proxy Protocol V1/V2. For introduction on the protocol, see Proxy Protocol V1/V2.
The origin can parse and obtain real client IPs with two methods based on the scenarios and deployment modes.
Method 1: If the TCP protocol is used on the origin, it is recommended to add a Nginx server that supports Proxy
Protocol V1/V2 in front of the application server. For details, see Obtaining Real Client IPs Through Nginx.
Method 2: If the UDP protocol is used on the origin, or if you want to directly parse the real client IPs under the TCP
protocol on the application server, you can parse the Proxy Protocol field on the application server by referring to thesample code in the Proxy Protocol. For details, see Parsing Real Client IPs on Application Server.

©2013-2022 Tencent Cloud. All rights reserved.

Page 47 of 77

Tencent Cloud EdgeOne

Method 1: Obtaining Real Client IPs Through
Nginx：

Last updated 2023-09-11 17:42:15

Overview
If the TCP protocol is used on the origin, it is recommended to add a Nginx server that supports Proxy Protocol V1/V2
in front of the application server to obtain real client IPs.
Note:
If the TCP protocol is used on the origin, and you want to directly parse the real client IPs on the application server,
please see Parsing Real Client IPs on Application Server.

Deployment Mode

As shown in the above diagram, you need to deploy a Nginx server in front of the application server to remove theProxy Protocol field. You can collect the real client IPs by analyzing Nginx logs on the Nginx server. At this time, you
can point the origin address to the Nginx service when you configure the origin address in the EdgeOne L4 proxyservice.

Directions
Step 1. Deploy Nginx service
Please select a Nginx version corresponding to the Proxy Protocol version you want to use.
For Proxy Protocol V1: Nginx Plus R11 and later versions, Nginx Open Source 1.11.4 and later versions.

©2013-2022 Tencent Cloud. All rights reserved.

Page 48 of 77

Tencent Cloud EdgeOne

For Proxy Protocol V2: Nginx Plus R16 and later versions, Nginx Open Source 1.13.11 and later versions.
For other Nginx versions, see Accepting the PROXY Protocol.
You need to install Nginx-1.18.0 and the stream module to enable L4 proxy service on Nginx. See installation
directions below.

# Install the nginx build environment
yum -y install gcc gcc-c++ autoconf automake
yum -y install zlib zlib-devel openssl openssl-devel pcre-devel# Decompress the source package
tar -zxvf nginx-1.18.0.tar.gz©2013-2022 Tencent Cloud. All rights reserved.

Page 49 of 77

Tencent Cloud EdgeOne# Enter the directory
cd nginx-1.18.0# Set nginx compilation and installation configuration (with `--with-stream`)./configure --prefix=/opt/nginx --sbin-path=/opt/nginx/sbin/nginx --conf-path=/opt/# Compilation
make# Installation
make install

Step 2: Configure the stream module in Nginx
If you select Nginx-1.18.0, you can run the following command to open the configuration file nginx.conf.

©2013-2022 Tencent Cloud. All rights reserved.

Page 50 of 77

Tencent Cloud EdgeOne

vi /opt/nginx/conf/nginx.conf
Configuration of the stream module is as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 51 of 77

Tencent Cloud EdgeOne

stream {# Set the log format, where `proxy_protocol_addr` is the client address obtaine
log_format basic '$proxy_protocol_addr -$remote_addr [$time_local] ''$protocol $bytes_sent $bytes_received ''$session_time';
access_log logs/stream.access.log basic;# upstream configuration
upstream RealServer {hash $remote_addr consistent;# 127.0.0.1:8888 is the IP address and port of the application server©2013-2022 Tencent Cloud. All rights reserved.

Page 52 of 77

Tencent Cloud EdgeOne

server 127.0.0.1:8888 max_fails=3 fail_timeout=30s;}# server configuration
server {# L4 listening port, which corresponds to the origin port configured in L4
listen 10000
proxy_protocol;
proxy_connect_timeout
proxy_timeout 3s;
proxy_pass RealServer;

1s;

}
}

Step 3: Configure L4 proxy forwarding rule
After configuring the Nginx service, you can modify the L4 proxy forwarding rule in the console. Change the origin
address to the IP of the current Nginx service, and change the origin port to the L4 listening port configured in step 2.
Select Proxy Protocol V1 or V2 for the Pass Client IP according to the forwarding protocol. For details, see Modifying
L4 Proxy Forwarding Rules.

Step 4: Simulate client requests and verify results
You can build the TCP service, and simulate client requests on another server to verify the results. A sample is as
below:
1. Create an HTTP service with Python on the current server to simulate the TCP service.

©2013-2022 Tencent Cloud. All rights reserved.

Page 53 of 77

Tencent Cloud EdgeOne# Based on python2
python2 -m SimpleHTTPServer 8888
# Based on python3
python3 -m http.server 8888
2. Build a client request on another server, and simulate the TCP request with a curl request.

©2013-2022 Tencent Cloud. All rights reserved.

Page 54 of 77

Tencent Cloud EdgeOne# Initiate an HTTP request with curl, where the domain is the L4 proxy domain, andcurl -i "http://d42f15b7a9b47488.davidjli.xyz.acc.edgeonedy1.com:8888/"
3. Check Nginx logs on the Nginx server:©2013-2022 Tencent Cloud. All rights reserved.

Page 55 of 77

Tencent Cloud EdgeOne

You can capture packets on the Nginx server and analyze the packets with Wireshark. After the TCP handshake iscompleted, the Proxy Protocol field is added in front of the first application data packet. Below is an example for Proxy
Protocol V1. ① refers to the L4 proxy egress IP, ② refers to the Nginx server IP, ③ refers to the protocol version, ④refers to the real client IP.

©2013-2022 Tencent Cloud. All rights reserved.

Page 56 of 77

Tencent Cloud EdgeOne

Method 2: Parsing Real Client IPs on
Application Server：

Last updated 2023-09-11 17:43:51

Scenarios
Scenario 1: If the UDP protocol is used on the origin, only Proxy Protocol V2 can be selected to pass the real client
IPs. In this case, you need to parse the Proxy Protocol V2 on the application server to obtain the real client IPs.
Scenario 2: If the TCP protocol is used on the origin, and you want to implement application judgment via the realclient IPs on the application server, you need to parse the Proxy Protocol V1/V2 on the application server to obtain thereal client IPs.

Deployment Diagram

As shown in the above diagram, you can configure L4 proxy via EdgeOne L4 proxy module to point to the application
server, and add the Proxy Protocol field to the application data by EdgeOne L4 proxy service. Parsing is implemented
on the application server.

Directions©2013-2022 Tencent Cloud. All rights reserved.

Page 57 of 77

Tencent Cloud EdgeOne

Step 1: Configure L4 proxy forwarding rule
Modify the L4 proxy forwarding rule in the console. You need to enter the origin address and origin port. If theforwarding protocol is UDP, select Proxy Protocol V2 for Pass client IP. If the forwarding protocol is TCP, you canselect Proxy Protocol V1 or V2. For details, see Modifying L4 Proxy Forwarding Rules.

Step 2: Obtain real client IPs on the application server
You need to parse the Proxy Protocol filed with reference to the sample code in the Proxy Protocol. For the format of
the client IPs, see Format of Real Client IPs Obtained Through Proxy Protocol V1/V2.

When the UDP protocol and Proxy Protocol V2 are selected, the Proxy Protocol field is added to the first UDP
datagram. In the figure below, ① refers to the L4 proxy egress IP, ② refers to the origin address, ③ refers to theprotocol version, ④ refers to the Proxy Protocol field, ⑤ refers to the real client IP address, and ⑥ refers to theapplication data.

©2013-2022 Tencent Cloud. All rights reserved.

Page 58 of 77

Tencent Cloud EdgeOne©2013-2022 Tencent Cloud. All rights reserved.

Page 59 of 77

Tencent Cloud EdgeOne

Format of Real Client IPs Obtained Through
Proxy Protocol V1/V2：

Last updated 2023-06-29 15:37:55

Proxy Protocol V1Proxy Protocol V1 supports TCPv4 and TCPv6, and adopts string format. See details below:©2013-2022 Tencent Cloud. All rights reserved.

Page 60 of 77

Tencent Cloud EdgeOne

PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\\r\\nYou can check the following information with Wireshark.

©2013-2022 Tencent Cloud. All rights reserved.

Page 61 of 77

Tencent Cloud EdgeOne

Proxy Protocol V2Proxy Protocol V2 supports TCPv4, TCPv6, UDPv4 and UDPv6, and adopts the binary format. See details below:

IPv4©2013-2022 Tencent Cloud. All rights reserved.

Page 62 of 77

Tencent Cloud EdgeOne

IPv6©2013-2022 Tencent Cloud. All rights reserved.

Page 63 of 77

Tencent Cloud EdgeOne©2013-2022 Tencent Cloud. All rights reserved.

Page 64 of 77

Tencent Cloud EdgeOne

Transmitting Client Real IP via SPP Protocol：

Last updated 2024-07-30 16:22:12

Application scenario
The SPP (Simple Proxy Protocol Header, hereinafter referred to as SPP) protocol is a custom header format used byproxy servers to transmit real client IP and other related information to backend servers. It is used for logging, access
control, CLB, fault troubleshooting, and other scenarios. The SPP header has a fixed length of 38 bytes, making it
simpler compared to the Proxy Protocol V2.
If your current backend business service is a UDP service and either already supports the SPP protocol or you prefera simpler parsing method, you can use the SPP protocol to transmit the client real IP. EdgeOne's layer 4 proxysupports transmitting the real client IP to the business server based on the SPP protocol standard. You can parse thisprotocol at the server end to obtain the real client IP and port.

EdgeOne SPP Protocol Handling Process
Request Access

As shown in the above diagram, when you use the SPP protocol to transmit the Client IP and Port, the EdgeOne Layer
4 proxy will automatically append the client’s real IP and Port in a fixed 38-byte length, following the SPP header
format, before each payload. You need to parse the SPP header field on the origin server to obtain the client’s real IP
and Port.

Origin server response©2013-2022 Tencent Cloud. All rights reserved.

Page 65 of 77

Tencent Cloud EdgeOne

As illustrated above, when the origin server responds, it must include the SPP header and return it to the EO Layer 4
proxy. The EO Layer 4 proxy will automatically uninstall the SPP header.
Note:
If the origin server does not return the SPP header, it will result in the EO Layer 4 proxy truncating the business data inthe payload.

Directions
Step 1: Configure Layer 4 Proxy Forwarding Rules
1. Log in into the EdgeOne console, click on Site List in the left sidebar. Subsequently, within the Site List, select the
Site you wish to configure.
2. On the site detail page, click L4 Proxy.
3. On the L4 Proxy page, select the L4 proxy instance you want to modify, and click Configure.
4. Select the Layer 4 proxy rule that requires passing the real client IP and click Edit.
5. Enter the corresponding business origin server address, origin server port, choose UDP for the forwarding protocol,
select Simple Proxy Protocol for passing Client IP, and click Save.

©2013-2022 Tencent Cloud. All rights reserved.

Page 66 of 77

Tencent Cloud EdgeOne

Step 2: Parse the SPP field on the origin server to obtain the real client IP
You can refer to SPP Protocol Header Format and Sample Code to parse the SPP field on the origin server. Whenusing the SPP protocol to transmit the real Client IP, the service packet data format obtained by the server is asfollows:

You canrefer to the following sample code to parse the business data and obtain the real Client IP.
GoC©2013-2022 Tencent Cloud. All rights reserved.

Page 67 of 77

Tencent Cloud EdgeOne

package main
import ("encoding/binary"
"fmt"
"net"
)
type NetworkConnection struct {Magic
uint16
ClientAddr net.IP©2013-2022 Tencent Cloud. All rights reserved.

Page 68 of 77

Tencent Cloud EdgeOne

ProxyAddr net.IP
ClientPort uint16
ProxyPort uint16}
func handleConn(conn *net.UDPConn) {buf := make([]byte, 1024)// Create a buffern, addr, err := conn.ReadFromUDP(buf) // Read the packet from the connectio
if err != nil {fmt.Println("Error reading from UDP connection:", err)
return}// Convert the received bytes to a NetworkConnection struct
nc := NetworkConnection{
Magic:
binary.BigEndian.Uint16(buf[0:2]),
ClientAddr: make(net.IP, net.IPv6len),
ProxyAddr: make(net.IP, net.IPv6len),}if nc.Magic == 0x56EC {copy(nc.ClientAddr, buf[2:18])
copy(nc.ProxyAddr, buf[18:34])
nc.ClientPort = binary.BigEndian.Uint16(buf[34:36])
nc.ProxyPort = binary.BigEndian.Uint16(buf[36:38])// Print SPP header information, including magic, client's real IP
fmt.Printf("Received packet:\\n")fmt.Printf("\\tmagic: %x\\n", nc.Magic)
fmt.Printf("\\tclient address: %s\\n", nc.ClientAddr.String())
fmt.Printf("\\tproxy address: %s\\n", nc.ProxyAddr.String())
fmt.Printf("\\tclient port: %d\\n", nc.ClientPort)
fmt.Printf("\\tproxy port: %d\\n", nc.ProxyPort)// Print the real and effective payload
fmt.Printf("\\tdata: %v\\n\\tcount: %v\\n", string(buf[38:n]), n)} else {// Print the real and effective payload
fmt.Printf("\\tdata: %v\\n\\tcount: %v\\n", string(buf[0:n]), n)}// Response package, note: The SPP 38-byte length must be returned unchange
response := make([]byte, n)copy(response, buf[0:n])_, err = conn.WriteToUDP(response, addr) // Send data
if err != nil {fmt.Println("Write to udp failed, err: ", err)}

©2013-2022 Tencent Cloud. All rights reserved.

Page 69 of 77

Tencent Cloud EdgeOne}
func main() {localAddr, _ := net.ResolveUDPAddr("udp", ":6666") // Create a UDP addressconn, err := net.ListenUDP("udp", localAddr)// Create a listener
if err != nil {panic("Failed to listen for UDP connections:" + err.Error())}
defer conn.Close() // Close the connection when donefor {
handleConn(conn) // Handle the incoming connection}}©2013-2022 Tencent Cloud. All rights reserved.

Page 70 of 77

Tencent Cloud EdgeOne#include <stdio.h>#include <stdlib.h>#include <string.h>#include <arpa/inet.h>#include <netinet/in.h>#include <sys/socket.h>#define BUF_SIZE 1024
struct NetworkConnection {uint16_t magic;
struct in6_addr clientAddr;
struct in6_addr proxyAddr;©2013-2022 Tencent Cloud. All rights reserved.

Page 71 of 77

Tencent Cloud EdgeOne

uint16_t clientPort;
uint16_t proxyPort;};
void handleConn(int sockfd) {struct sockaddr_in clientAddr;
socklen_t addrLen = sizeof(clientAddr);
unsigned char buf[BUF_SIZE];
ssize_t n = recvfrom(sockfd, buf, BUF_SIZE, 0, (struct sockaddr *)&clientAddr,
if (n < 0) {perror("Error reading from UDP connection");return;}// Convert the received bytes to a NetworkConnection struct
struct NetworkConnection nc;
nc.magic = ntohs(*(uint16_t *)buf);
if (nc.magic == 0x56EC) { // Magic value 0x56EC indicates an SPP header
memcpy(&nc.clientAddr, buf + 2, 16);
memcpy(&nc.proxyAddr, buf + 18, 16);
nc.clientPort = ntohs(*(uint16_t *)(buf + 34));
nc.proxyPort = ntohs(*(uint16_t *)(buf + 36));
printf("Received packet:\\n");printf("\\tmagic: %x\\n", nc.magic);char clientIp[INET6_ADDRSTRLEN];
char proxyIp[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &nc.clientAddr, clientIp, INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, &nc.proxyAddr, proxyIp, INET6_ADDRSTRLEN);// Print SPP header information, including magic, client's real IP and port
printf("\\tclient address: %s\\n", clientIp);
printf("\\tproxy address: %s\\n", proxyIp);
printf("\\tclient port: %d\\n", nc.clientPort);
printf("\\tproxy port: %d\\n", nc.proxyPort);// Print the actual payload
printf("\\tdata: %.*s\\n\\tcount: %zd\\n", (int)(n - 38), buf + 38, n);} else {printf("\\tdata: %.*s\\n\\tcount: %zd\\n", (int)n, buf, n);}// Send response packet, note: the SPP 38-byte length must be returned as-issendto(sockfd, buf, n, 0, (struct sockaddr *)&clientAddr, addrLen);}int main() {int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {perror("Failed to create socket");exit(EXIT_FAILURE);}// Create a UDP address using the local address and port

©2013-2022 Tencent Cloud. All rights reserved.

Page 72 of 77

Tencent Cloud EdgeOne

struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(6666);
if (bind(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) {perror("Failed to bind");exit(EXIT_FAILURE);}
while (1) {handleConn(sockfd);}}

Step 3: Testing and Validation
You can use a server as the client, construct client requests, and use the nc command to simulate UDP requests. The
details of the command are as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 73 of 77

Tencent Cloud EdgeOne

echo "Hello Server" | nc -w 1 -u <IP/DOMAIN> <PORT>
Here, IP/Domain refers to the IP or domain of your fourth-layer proxy instance, which you can view in the EdgeOne
console. Port refers to the forward port configured for the rule in Step 1.

©2013-2022 Tencent Cloud. All rights reserved.

Page 74 of 77

Tencent Cloud EdgeOne

The server receives the request and parses the Client IP address as follows:

Related References
SPP Protocol Header Format©2013-2022 Tencent Cloud. All rights reserved.

Page 75 of 77

Tencent Cloud EdgeOne

Magic Number
In the SPP Protocol format, Magic Number is 16 bits with a fixed value of 0x56EC, mainly used to identify the SPP
Protocol. It also defines that the SPP protocol header is a fixed length of 38 bytes.
Client Address
The client's request IP address is 128 bits long. If initiated by an IPV4 client, the value represents IPV4; if initiated by
an IPV6 client, the value represents IPV6.
Proxy Address
The proxy server's IP address is 128 bits long and can be parsed in the same way as the Client Address.
Client Port
The port for the client to send UDP packets is 16 bits long.
Proxy Port
The port for the proxy server to receive UDP packets is 16 bits long.
payload©2013-2022 Tencent Cloud. All rights reserved.

Page 76 of 77

Tencent Cloud EdgeOne

Payload, the data following the header in the data packet.

©2013-2022 Tencent Cloud. All rights reserved.

Page 77 of 77