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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  100  101  102  [103]  104  105  ...
NoWriterDateCnt.TitleFile(s)
11385정성태12/5/201732043VC++: 121. DXGI를 이용한 윈도우 화면 캡처 소스 코드(Visual C++) [16]파일 다운로드1
11384정성태12/5/201721454오류 유형: 437. Visual C++ - Cannot open include file: 'SDKDDKVer.h'
11383정성태12/4/201724196디버깅 기술: 110. 비동기 코드 실행 중 예외로 인한 ASP.NET 프로세스 비정상 종료 현상 [1]
11382정성태12/4/201722983오류 유형: 436. System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired 예외 발생 시 "[Pre-Login] initialization=48; handshake=1944;" 값의 의미
11381정성태11/30/201719530.NET Framework: 702. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)파일 다운로드1
11380정성태11/30/201719572디버깅 기술: 109. windbg - (x64에서의 인자 값 추적을 이용한) Thread.Abort 시 대상이 되는 스레드를 식별하는 방법
11379정성태11/30/201719559오류 유형: 435. System.Web.HttpException - Session state has created a session id, but cannot save it because the response was already flushed by the application.
11378정성태11/29/201721382.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법 [1]파일 다운로드1
11377정성태11/29/201720913.NET Framework: 700. CommonOpenFileDialog 사용 시 사용자가 선택한 파일 목록을 구하는 방법 [3]파일 다운로드1
11376정성태11/28/201725520VS.NET IDE: 123. Visual Studio 편집기의 \r\n (crlf) 개행을 \n으로 폴더 단위로 설정하는 방법
11375정성태11/28/201719516오류 유형: 434. Visual Studio로 ASP.NET 디버깅 중 System.Web.HttpException - Could not load type 오류
11374정성태11/27/201725280사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201724292오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201726918사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201720746오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201720912오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201722691사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
11368정성태11/25/201728158.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201728464개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201720212오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201721857오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201724476사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201724536사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201720218오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201723211오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201723545오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
... 91  92  93  94  95  96  97  98  99  100  101  102  [103]  104  105  ...