Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

파이썬 - Linux 환경 + TCP 서버 소켓을 사용하는 프로세스 종료 후 재실행하는 경우 "OSError: [Errno 98] Address already in use" 오류 발생

간단한 예제를 하나 만들어 볼까요?

import socketserver

server = None


class MyTCPHandler(socketserver.BaseRequestHandler):

    def handle(self):
        pieces = [b'']
        total = 0
        while b'\n' not in pieces[-1] and total < 10_000:
            pieces.append(self.request.recv(2000))
            total += len(pieces[-1])
        self.data = b''.join(pieces)
        print(f"Received from {self.client_address[0]}:")
        # just send back the same data, but upper-cased
        self.request.sendall(bytes("HTTP/1.1 200 OK\r\n\r\n", "utf-8"))
        self.request.sendall(self.data.upper())


def start_app():
    print('my app started')

    global server
    server = socketserver.ThreadingTCPServer(("127.0.0.1", 8080), MyTCPHandler)
    try:
        server.serve_forever()
    except:
        print('server closing...')
        server.server_close()
        print('server closed')


if __name__ == '__main__':
    start_app()

실행 후, (웹 브라우저 등을 이용해) HTTP 요청을 보내 정상 동작하는 것을 확인하고 Ctrl+C로 프로세스를 종료합니다. (혹은 kill -9 [pid] 명령어로 종료하거나!)

// 만약 한 번이라도 요청을 보내지 않으면 아래의 현상이 발생하지 않습니다.

$ python main.py
my app started
Received from 127.0.0.1:
^Cserver closing...
server closed

이후, 곧바로 위의 예제를 다시 실행하면 이런 오류가 발생합니다.

$ python main.py
my app started
Traceback (most recent call last):
  File "main.py", line 63, in <module>
    start_app()
  File "main.py", line 55, in start_app
    server = socketserver.ThreadingTCPServer(("127.0.0.1", 8080), MyTCPHandler)
  File "/home/testusr/miniconda3/envs/py38build/lib/python3.8/socketserver.py", line 452, in __init__
    self.server_bind()
  File "/home/testusr/miniconda3/envs/py38build/lib/python3.8/socketserver.py", line 466, in server_bind
    self.socket.bind(self.server_address)
OSError: [Errno 98] Address already in use

문서를 보니까, shutdown 함수가 있는데,

socketserver — A framework for network servers
; https://docs.python.org/3/library/socketserver.html#socketserver.BaseServer.shutdown

혹시 이걸 부르면 어떨까 싶어 테스트했지만,

def start_app():
    print('my app started')

    global server
    server = socketserver.ThreadingTCPServer(("127.0.0.1", 8080), MyTCPHandler)
    try:
        server.serve_forever()
    except:
        server.shutdown()

마찬가지입니다. ^^; 이때 netstat로 확인을 해보면 서버 소켓은 없지만 accept로 받았던 클라이언트 소켓이 TIME_WAIT 상태로 남아 있는 것을 확인할 수 있습니다.

// sudo apt install net-tools -y

$ netstat -ano | grep 8080
tcp        0      0 127.0.0.1:8080          127.0.0.1:54042         TIME_WAIT   timewait (57.05/0/0)

보통 TIME_WAIT 이후 2MSL(Maximum Segment Lifetime) 시간이 지나야 완전하게 소켓이 정리되는데요, (제가 테스트 중인) 리눅스 환경의 경우 60초로 설정돼 있습니다.

$ cat /proc/sys/net/ipv4/tcp_fin_timeout
60

혹은 netstat 명령어의 출력에 보면 "timewait (57.05/0/0)"라고 나오는데, 바로 저 "57.05"가 TIME_WAIT이 정리될 때까지의 남은 시간(초)을 의미하므로 그걸로도 추측할 수 있습니다.




어쨌든, 이런 경우 전역 설정을 바꾸는 것은 조금 부담스러운데요,

python TCPServer address already in use but I close the server and I use `allow_reuse_address`
; https://stackoverflow.com/questions/15260558/python-tcpserver-address-already-in-use-but-i-close-the-server-and-i-use-allow

그렇군요, 리눅스도 socket reuse 옵션을 통해 곧바로 재사용할 수 있게 설정할 수 있습니다.

import socketserver

socketserver.TCPServer.allow_reuse_address = True

# ...[생략]...

if __name__ == '__main__':
    start_app()

이후, 종료/재실행을 해보면 정상적으로 서버 소켓이 바인딩되는 것을 확인할 수 있습니다.




그런데, 여기서 흥미로운 점이 하나 있는데요, 저 현상이 C#으로는 재현이 안 된다는 점입니다. 일례로, 다음과 같이 작성한 후,

internal class Program
{
    static void Main(string[] args)
    {
        using (Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 8080);
            serverSocket.Bind(endPoint);

            serverSocket.Listen(10);

            Console.WriteLine("Server listening on port 8080...");

            while (true)
            {
                using (Socket clnt = serverSocket.Accept())
                {
                    Console.WriteLine("Client connected.");
                    clnt.Receive(new byte[4096]);

                    clnt.Send(System.Text.Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\n\r\nTEST IS GOOD"));
                }
            }
        }
    }
}

파이썬과 동일하게 테스트를 해보면 분명히 TIME_WAIT 상태의 클라이언트가 남아 있지만,

$ netstat -ano | grep 8080
tcp        0      0 127.0.0.1:8080          127.0.0.1:35742         TIME_WAIT   timewait (45.52/0/0)

재실행하면 serverSocket.Bind 코드가 잘 실행됩니다. (즉, 파이썬과는 달리 "Address already in use" 오류가 발생하지 않습니다.)

더욱 흥미로운 점이 있는데요, 저렇게 C#으로 작성한 서버 소켓을 실행/Accept/종료한 다음 이어서 파이썬을 실행시키면 "Address already in use" 오류가 발생한다는 점입니다.

// 정상 동작
C# Server 바인딩/Accept/종료 => C# Server 바인딩

// 오류 발생 (OSError: [Errno 98] Address already in use)
C# Server 바인딩/Accept/종료 => 파이썬 Server 바인딩 (allow_reuse_address = False)

반대의 경우에도 (allow_reuse_address = False가 적용된) 파이썬 소켓의 영향으로 C# 서버 소켓이 바인딩되지 않는데요,

// 오류 발생 (OSError: [Errno 98] Address already in use)
파이썬 Server 바인딩/Accept/종료 => 파이썬 Server 바인딩

// 오류 발생 (System.Net.Sockets.SocketException (98): Address already in use)
파이썬 Server 바인딩/Accept/종료 => C# Server 바인딩

도대체 파이썬의 serversocket은 어떤 동작을 추가로 하는 걸까요? ^^;




참고로, C#의 경우 ReuseAddress 옵션은 기본값이 false로 나옵니다.

using (Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
    object? objValue = serverSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress);
    Console.WriteLine($"ReuseAddress: {objValue}"); // ReuseAddress: 0

    IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 8080);
    serverSocket.Bind(endPoint);

    // ...[생략]...

    while (true)
    {
        using (Socket clnt = serverSocket.Accept())
        {
            objValue = clnt.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress);
            Console.WriteLine($"ReuseAddress: {objValue}"); // ReuseAddress: 0

            // ...[생략]...
        }
    }
}

다시 말해 파이썬의 경우에는 저 값을 true로 설정하지 않으면 서버 소켓을 재사용할 수 없었지만, C#은 기본값이 false여도 서버 소켓을 재사용할 수 있었습니다. (물론, 파이썬 다음에 실행하면 C# 서버 소켓도 바인딩할 수 없었지만.)

혹시, 저런 현상이 왜 파이썬에서 나타나는지 아시는 분은 덧글 부탁드립니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/10/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13676정성태7/14/20248259Linux: 75. gdb에서 glibc의 함수에 Breakpoint 걸기
13675정성태7/13/202410478C/C++: 166. C/C++ - DLL에서 template 함수를 export하는 방법 [1]파일 다운로드1
13674정성태7/13/20249097오류 유형: 915. Unhandled Exception: Microsoft.Diagnostics.NETCore.Client.ServerNotAvailableException: Unable to connect to Process
13673정성태7/11/20249848닷넷: 2275. C# 13 - (1) 신규 이스케이프 시퀀스 '\e'파일 다운로드1
13672정성태7/10/20247913닷넷: 2274. IIS - (프로세스 종료 없는) AppDomain Recycle
13671정성태7/10/20248198오류 유형: 914. Package ca-certificates is not installed.
13669정성태7/9/20248281오류 유형: 913. C# - AOT StaticExecutable 정적 링킹 시 빌드 오류
13668정성태7/8/20248551개발 환경 구성: 716. Hyper-V - Ubuntu 22.04 Generation 2 유형의 VM 설치
13667정성태7/7/20247194닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20248982Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20249265Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20248396닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20248239닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20248158Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20248941오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20248874개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20249548개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20248685닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20249376Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20248934닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20248663오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20248837닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/202410340닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20249797닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20249828개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20248943오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...