refactor: replace getPublicIpWithFallback with getLocalServerIp for improved local IP retrieval

This commit is contained in:
Mauricio Siu
2025-09-20 23:57:38 -06:00
parent e1ce54c159
commit ca243d7259
2 changed files with 24 additions and 4 deletions

View File

@@ -7,7 +7,7 @@ import {
} from "@dokploy/server";
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { getPublicIpWithFallback } from "@/server/wss/terminal";
import { getLocalServerIp } from "@/server/wss/terminal";
import { createTRPCRouter, protectedProcedure } from "../trpc";
export const clusterRouter = createTRPCRouter({
getNodes: protectedProcedure
@@ -61,7 +61,7 @@ export const clusterRouter = createTRPCRouter({
const result = await docker.swarmInspect();
const docker_version = await docker.version();
let ip = await getPublicIpWithFallback();
let ip = await getLocalServerIp();
if (input.serverId) {
const server = await findServerById(input.serverId);
ip = server?.ipAddress;
@@ -85,7 +85,7 @@ export const clusterRouter = createTRPCRouter({
const result = await docker.swarmInspect();
const docker_version = await docker.version();
let ip = await getPublicIpWithFallback();
let ip = await getLocalServerIp();
if (input.serverId) {
const server = await findServerById(input.serverId);
ip = server?.ipAddress;

View File

@@ -1,5 +1,10 @@
import type http from "node:http";
import { findServerById, IS_CLOUD, validateRequest } from "@dokploy/server";
import {
execAsync,
findServerById,
IS_CLOUD,
validateRequest,
} from "@dokploy/server";
import { publicIpv4, publicIpv6 } from "public-ip";
import { Client, type ConnectConfig } from "ssh2";
import { WebSocketServer } from "ws";
@@ -44,6 +49,21 @@ export const getPublicIpWithFallback = async () => {
return ip;
};
export const getLocalServerIp = async () => {
try {
const command = `ip addr show | grep -E "inet (192\.168\.|10\.|172\.1[6-9]\.|172\.2[0-9]\.|172\.3[0-1]\.)" | head -n1 | awk '{print $2}' | cut -d/ -f1`;
const { stdout } = await execAsync(command);
const ip = stdout.trim();
return (
ip ||
"We were unable to obtain the local server IP, please use your private IP address"
);
} catch (error) {
console.error("Error to obtain local server IP", error);
return "We were unable to obtain the local server IP, please use your private IP address";
}
};
export const setupTerminalWebSocketServer = (
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
) => {