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)
13926정성태5/14/20252033개발 환경 구성: 743. LLM과 윈도우의 만남 - Desktop AgentOS UFO² 기본 환경 구성
13925정성태5/12/20252107닷넷: 2333. C# - (Console 유형의 프로젝트에서) Clipboard 연동파일 다운로드1
13924정성태5/8/20251948닷넷: 2332. C# - (JetBrains Omea Reader 대상으로) 런타임 시에 메서드 가로채기 [2]파일 다운로드1
13923정성태5/5/20251693스크립트: 74. 파이썬 - C# - Python.NET의 RunSimpleScript, Exec, Eval 차이점파일 다운로드1
13922정성태5/3/20251978스크립트: 73. 파이썬 - Windows embeddable package 버전에서 tkinter 환경 구성
13921정성태5/3/20252536오류 유형: 952. 듀얼 채널 메모리 정렬을 지키지 않은 컴퓨터의 Windows 비정상 종료 현상(Blue Screen) [2]
13920정성태5/3/20252615오류 유형: 951. Typed DataSet 생성 중 "Failed to open a connection to the database" 오류
13919정성태5/2/20252103VS.NET IDE: 201. C# - Typed DataSet(XSD)를 위한 연결 문자열 암호화 [1]파일 다운로드1
13918정성태5/2/20252554VS.NET IDE: 200. C# - app.config 파일의 출력을 Configuration(Debug/Release)에 따라 제어하는 방법파일 다운로드1
13917정성태4/30/20251886VS.NET IDE: 199. Directory.Build.props에 정의한 속성에 대해 Condition 제약으로 값을 변경하는 방법
13916정성태4/23/20251551디버깅 기술: 221. WinDbg 분석 사례 - ASP.NET HttpCookieCollection을 다중 스레드에서 사용할 경우 무한 루프 현상 - 두 번째 이야기
13915정성태4/13/20252827닷넷: 2331. C# - 실행 시에 메서드 가로채기 (.NET 9)파일 다운로드1
13914정성태4/11/20253188디버깅 기술: 220. windbg 분석 사례 - x86 ASP.NET 웹 응용 프로그램의 CPU 100% 현상 (4)
13913정성태4/10/20251947오류 유형: 950. Process Explorer - 64비트 윈도우에서 32비트 프로세스의 덤프를 뜰 때 "Error writing dump file: Access is denied." 오류
13912정성태4/9/20251666닷넷: 2330. C# - 실행 시에 메서드 가로채기 (.NET 5 ~ .NET 8)파일 다운로드1
13911정성태4/8/20251991오류 유형: 949. WinDbg - .NET Core/5+ 응용 프로그램 디버깅 시 sos 확장을 자동으로 로드하지 못하는 문제
13910정성태4/8/20252208디버깅 기술: 219. WinDbg - 명령어 내에서 환경 변수 사용법
13909정성태4/7/20253304닷넷: 2329. C# - 실행 시에 메서드 가로채기 (.NET Framework 4.8)파일 다운로드1
13908정성태4/2/20253463닷넷: 2328. C# - MailKit: SMTP, POP3, IMAP 지원 라이브러리
13907정성태3/29/20253698VS.NET IDE: 198. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C# 프로젝트의 출력 경로 변경하기
13906정성태3/27/20253813닷넷: 2327. C# - 초기화되지 않은 메모리에 접근하는 버그?파일 다운로드1
13905정성태3/26/20253782Windows: 281. C++ - Windows / Critical Section의 안정화를 위해 도입된 "Keyed Event"파일 다운로드1
13904정성태3/25/20253105디버깅 기술: 218. Windbg로 살펴보는 Win32 Critical Section파일 다운로드1
13903정성태3/24/20252302VS.NET IDE: 197. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C++ 프로젝트의 출력 경로 변경하기
13902정성태3/24/20252773개발 환경 구성: 742. Oracle - 테스트용 hr 계정 및 데이터 생성파일 다운로드1
13901정성태3/9/20253028Windows: 280. Hyper-V의 3가지 Thread Scheduler (Classic, Core, Root)
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...