Build a server without a fixed IP

A nearly perfect solution

Background: A server with a bandwidth of about 20 MB is required, but Alibaba Cloud’s cloud server is too expensive. If the bandwidth is high, it will be even more expensive. But using the local server directly, there is no corporate public network fixed IP, only dynamic public network IP, which can only be solved by ddns. However, the minimum ttl duration of ddns for non-enterprises is 10 minutes. The ttl is the domain name resolution result (ip address) during operation. The length of time to save on dns. If a user accesses through the domain name within 10 minutes after the update, the operator’s DNS will be directed to an IP address that does not exist in the server. The real IP cannot be updated in time. The server cannot be accessed.

No business so need a cheap solution

↓↓↓

Need to prepare: an Alibaba Cloud ecs instance (check Alibaba Cloud to allocate public IP), the local network is a public IP, and an Alibaba Cloud domain name (to facilitate subsequent upgrades and prevent changes in the resolution server IP, used to resolve aliyunecs, if not, use Alibaba It is also possible to directly access the IP of cloud ecs, but it is not safe)

Implementation method: Build a real database on a local server, run everything on the local server, and then write an additional program to obtain the local IP, upload it to Alibaba Cloud through ajax, and detect it every second. If it changes, Upload to Alibaba Cloud ECS.

1-1. Method to obtain the local IP in real time and print it on the browser page (JavaScript requires the browser to open webrtc)

<!DOCTYPE html>

<html>

<head>

</head>

<body>

    <h1>Real-time local IP address</h1>

    <p id="ip"></p>



    <script>

        function getLocalIP(callback) {

            const RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

            const rtc = new RTCPeerConnection({iceServers: []});

            const noop = function(){};

            

            rtc.createDataChannel('');



            rtc.createOffer(function(sessionDescription) {

                rtc.setLocalDescription(sessionDescription, noop, noop);

            }, noop);



            rtc.onicecandidate = function(event) {

                if (event.candidate) {

                    const ipRegex = /\b(?:\d{1,3}\.){3}\d{1,3}\b/;

                    const match = ipRegex.exec(event.candidate.candidate);

                    const localIP = match ? match[0] : 'unknown';

                    callback(localIP);

                    rtc.onicecandidate = noop;

                }

            };

        }



        setInterval(function() {

            getLocalIP(function(localIP) {

                document.getElementById("ip").innerHTML = "Local IP Address: " + localIP;

            });

        }, 1000); // Update frequency (in milliseconds)



    </script>

</body>

</html>

1-2. Obtain local IP in real time and upload (JavaScript + html implementation)

//The following is an example of front-end code implemented in plain JavaScript, interacting with the following Java server and storing and replacing strings:

html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>String Storage Client</title>
</head>
<body>
    <h1>String Storage Client</h1>
    
    <div id="status"></div>
    
    <label for="password">Access Password:</label>
    <input type="password" id="password">
    
    <br>
    
    <label for="newString">New String:</label>
    <input type="text" id="newString">
    
    <br><br>
    
    <button onclick="getStoreString()">Get Stored String</button>
    
    <br><br>
    
    <button onclick="updateString()">Update String</button>
    
    <script>
        const serverUrl = "http://localhost:8080";
        
        function sendHttpRequest(url, method, data, successCallback, errorCallback) {
            const xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        successCallback(xhr.responseText);
                    } else {
                        errorCallback(xhr.responseText);
                    }
                }
            };
            xhr.send(data);
        }
        
        function getStoreString() {
            const password = document.getElementById("password").value;
            
            sendHttpRequest(serverUrl, "POST", password, function(response) {
                document.getElementById("status").textContent = "Stored String: " + response;
            }, function(error) {
                document.getElementById("status").textContent = "Error: " + error;
            });
        }
        
        function updateString() {
            const password = document.getElementById("password").value;
            const newString = document.getElementById("newString").value;
            
            const requestData = password + "\\
" + newString;

            sendHttpRequest(serverUrl, "POST", requestData, function(response) {
                document.getElementById("status").textContent = "Update Successful: " + response;
            }, function(error) {
                document.getElementById("status").textContent = "Error: " + error;
            });
        }
    </script>
</body>
</html>

//This front-end code uses ordinary JavaScript to send XMLHttpRequest requests and
//Server interacts. There are two input boxes on the page, one is used to enter the access password, and the other
//One for entering a new string. Clicking the "Get Stored String" button will send the password
//Verify the server and display the stored string returned by the server on the page.
//Clicking the "Update String" button will send the password and new string to the server at the same time to replace the string stored in the server.

//Please make sure to modify the `serverUrl` variable according to the address of the actual server to ensure that it matches the URL address of the Java server. 

1-3 The cloud server monitors the real IP sent by the real server (Java implementation)

The following is a sample server written in Java, which can store the string sent by the front end and verify the access password. When the front end sends the string later, it will replace the string stored in the server:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;



public class StringStorageServer {

    private static final int PORT = 8080;

    private static final String ACCESS_PASSWORD = "password";

    private static String storedString = "initial_string";



    public static void main(String[] args) {

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {

            System.out.println("Server started, waiting for client connection...");



            while (true) {

                Socket clientSocket = serverSocket.accept();

                System.out.println("Client connected from: " + clientSocket.getInetAddress());



                PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);

                BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));



                // Check access password

                String requestPassword = reader.readLine();

                if (!ACCESS_PASSWORD.equals(requestPassword)) {

                    System.out.println("Access password incorrect!");

                    writer.println("Access password incorrect!");

                    clientSocket.close();

                    continue;

                }



                // Send current stored string to client

                writer.println(storedString);



                //Receive and store new string from client

                String newString = reader.readLine();

                if (newString != null & amp; & amp; !newString.trim().isEmpty()) {

                    storedString = newString;

                    System.out.println("New string received: " + storedString);

                    writer.println("String stored successfully.");

                } else {

                    writer.println("Empty string received.");

                }



                clientSocket.close();

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}



//This server will listen to port 8080 and wait for client connections. The client will send two lines of information, the first line is the access password,
//The second line is a string. The server will verify the password. If the password is incorrect, it will return an error message and disconnect.
//Otherwise, the stored string will be processed and stored, and then the corresponding information will be returned.

//Remember, this is just a simple example server, no security checksum error handling is done. In an actual production environment,
//Appropriate security measures and error handling mechanisms also need to be added.

//Please make sure to modify the `serverUrl` variable according to the address of the actual server to ensure that it matches the URL address of the Java server
//match. 

Alibaba Cloud esc only builds a backend program that receives and saves this string. If a new one is sent, replace this string

Result: The user opens the program and first accesses it through the domain name. The domain name will be directed to the Alibaba Cloud ecs cloud server. The server will return the real server IP address. At this time, the user can establish contact with the server with the real IP. After that, every time the user opens a new page, repeat the above operation (visit through the domain name first

Obtain the ip, and then load resources according to this ip), the URL addresses used are all strings corresponding to this ip