gethostid 在 docker 容器中的行为会有所不同。
主机操作系统:Ubuntu 20.04
容器操作系统:Ubuntu 20.04
用于连接 VPN 的软件:SonicWall NetExtender 10.2.845(也用 8.6.801 复制)
Docker运行命令:
docker run -it --rm --network="host" test_gethostid_vpn:latest
在此容器中 gethostid 需要 5 秒才能返回 0。 如果删除 --network="host" 选项或停止 netExtender,问题就会消失。
main.cpp 在我的容器中运行:
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <chrono>
int main(int* argc, char** argv)
{
auto startPoint = std::chrono::steady_clock::now();
long hostid = gethostid();
auto endPoint = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(endPoint - startPoint).count();
std::cout << "duration = " << duration << " [ms]" << std::endl;
std::cout << "hostid = " << hostid << std::endl;
std::cout << "errno = " << std::strerror(errno) << std::endl;
return 0;
}
CMakeLists.txt:
cmake_minimum_required(VERSION 3.16)
project(test_gethostid)
set(CMAKE_CXX_STANDARD 17)
add_executable(test_gethostid main.cpp)
Dockerfile:
FROM ubuntu:20.04
# Non interactive apt
# https://stackoverflow.com/questions/44331836/apt-get-install-tzdata-noninteractive
ENV TZ=Europe/Paris
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get upgrade -y && apt-get install -y cmake build-essential
COPY . /testcpp
WORKDIR /testcpp/build
RUN cmake ..
RUN make -j $(nproc)
ENTRYPOINT [ "./test_gethostid" ]
通过与容器共享 /etc/hostid 解决了问题:
docker run -it --rm -v /etc/hostid:/etc/hostid --network="host" test_gethostid_vpn:latest