Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
(시리즈 글이 8개 있습니다.)
개발 환경 구성: 533. Wireshark + C#으로 확인하는 TCP 통신의 MSS(Maximum Segment Size) - 리눅스 환경
; https://www.sysnet.pe.kr/2/0/12527

개발 환경 구성: 534. Wireshark + C#으로 확인하는 TCP 통신의 MSS(Maximum Segment Size) - 윈도우 환경
; https://www.sysnet.pe.kr/2/0/12528

개발 환경 구성: 535. Wireshark + C#으로 확인하는 TCP 통신의 MIN RTO
; https://www.sysnet.pe.kr/2/0/12529

개발 환경 구성: 536. Wireshark + C#으로 확인하는 TCP 통신의 Receive Window
; https://www.sysnet.pe.kr/2/0/12530

개발 환경 구성: 538. Wireshark + C#으로 확인하는 ReceiveBufferSize(SO_RCVBUF), SendBufferSize(SO_SNDBUF)
; https://www.sysnet.pe.kr/2/0/12532

개발 환경 구성: 539. Wireshark + C/C++로 확인하는 TCP 연결에서의 shutdown 동작
; https://www.sysnet.pe.kr/2/0/12533

개발 환경 구성: 540. Wireshark + C/C++로 확인하는 TCP 연결에서의 closesocket 동작
; https://www.sysnet.pe.kr/2/0/12534

개발 환경 구성: 541.  Wireshark로 확인하는 LSO(Large Send Offload), RSC(Receive Segment Coalescing) 옵션
; https://www.sysnet.pe.kr/2/0/12535




Wireshark + C#으로 확인하는 ReceiveBufferSize(SO_RCVBUF), SendBufferSize(SO_SNDBUF)

Socket 타입의 ReceiveBufferSize/SendBufferSize는,

Socket.ReceiveBufferSize Property
; https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.receivebuffersize

Socket.SendBufferSize Property
; https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.sendbuffersize

내부적으로 getsockopt, setsockopt로 구현합니다.

// SOL_SOCKET == 0xffff
// SO_SNDBUF == 0x1001
// SO_RCVBUF == 0x1002

int iOptVal = 0;
int iOptLen = sizeof(iOptLen);
getsockopt(client.Handle, SOL_SOCKET, SO_SNDBUF, (char *) &iOptVal, &iOptLen);
setsockopt(client.Handle, SOL_SOCKET, SO_SNDBUF, (char *) &iOptVal, iOptLen);

각각의 값이 어떤 기능을 하는지 찾아 보면,

Design issues - Sending small data segments over TCP with Winsock
; https://learn.microsoft.com/en-us/troubleshoot/windows/win32/data-segment-tcp-winsock

To optimize performance at the application layer, Winsock copies data buffers from application send calls to a Winsock kernel buffer. Then, the stack uses its own heuristics (such as Nagle algorithm) to determine when to actually put the packet on the wire. You can change the amount of Winsock kernel buffer allocated to the socket using the SO_SNDBUF option (it's 8K by default). If necessary, Winsock can buffer more than the SO_SNDBUF buffer size. In most cases, the send completion in the application only indicates the data buffer in an application send call is copied to the Winsock kernel buffer and doesn't indicate that the data has hit the network medium. The only exception is when you disable the Winsock buffering by setting SO_SNDBUF to 0.


SO_RCVBUF
; https://learn.microsoft.com/en-us/windows-hardware/drivers/network/so-rcvbuf

The SO_RCVBUF socket option determines the size of a socket's receive buffer that is used by the underlying transport.

If this socket option is set on a listening socket, all incoming connections that are accepted on that listening socket have their receive buffer set to the same size that is specified for the listening socket.


이렇게 정리해 볼 수 있습니다.

* SO_SNDBUF
    - SO_SNDBUF로 커널 내 송신 버퍼 크기 지정(즉, device driver 내에 non-paged pool 메모리를 할당)
    - 기본값 8K, 필요하다면 Winsock은 지정한 크기보다 큰 버퍼를 운영
    - 0으로 설정하면 버퍼링 없이 데이터 전달
    - send 호출 시 사용자 데이터를 커널 내 버퍼에 복사
    - send 호출이 반환되었다는 것은, 전달한 데이터가 커널 내 버퍼에 복사된 것을 의미(즉, 아직 수신 측으로 전달은 안 되었을 가능성 존재)

* SO_RCVBUF
    - SO_RCVBUF로 커널 내 수신 버퍼 크기 지정
    - recv 호출 시 커널 내 수신 버퍼의 내용을 사용자가 전달한 버퍼에 복사
    - accept로 반환한 자식 소켓의 기본값으로 서버 소켓을 따르지만 별도 설정도 가능

이쪽 분야가 워낙 빠르게 변화하다 보니, 저렇게 문서에 나와 있어도 사실 믿을 수가 없습니다. 그래서 가능하면 코드로 직접 테스트를 하는 것이 좋은데요, 우선 크기 관련해서는, 문서상으로 기본 크기가 각각 8192라고 하지만 실제로 테스트해 보면 환경마다 다르게 나옵니다. 가령 같은 Ubuntu 20.04의 경우에도,

Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

client.Connect("...", 15000);
Console.WriteLine($"Recv: {client.ReceiveBufferSize}, Send: {client.SendBufferSize}");

/* 출력 결과
[물리 머신에 설치한 Ubuntu 20.04]
Recv: 131072, Send: 332800

[Oracle Cloud의 VM - Ubuntu 20.04]
Recv: 131072, Send: 87040
*/

서로 다른 결과를 볼 수 있습니다. 참고로 Window 10의 경우에는 Recv/Send 모두 65,536으로 나오고 다음의 gist 코드 주석을 보면,

daverigby/socket_buffer_sizes
; https://gist.github.com/daverigby/ab6f2ef11b92b639c000bc0d2d5cf42c

마찬가지로 제각각인 버퍼 크기를 확인할 수 있습니다.

Linux:
initial rcvbuf: 87380
initial sndbuf: 16384
set rcvbuf to 1747600
set sndbuf to 327680
accepted connection
new rcvbuf: 425984
new sndbuf: 425984

OS X:
initial rcvbuf: 131072
initial sndbuf: 131072
set rcvbuf to 2621440
set sndbuf to 2621440
accepted connection
new rcvbuf: 2629452
new sndbuf: 2629452

Windows 7:
initial rcvbuf: 8192
initial sndbuf: 8192
set rcvbuf to 163840
set sndbuf to 163840
accepted connection
new rcvbuf: 163840
new sndvbuf: 163840

또한, Linux/OS X의 결과를 보면 서버 소켓에 rcvbuf/sndbuf 크기를 변경했지만 accept가 반환한 소켓에는 이를 상속받고 있지 않습니다. 게다가 리눅스의 경우 버퍼 크기를 설정하면 실제로 저장하는 크기는 2배가 된다고 합니다.

Understanding set/getsockopt SO_SNDBUF size doubles
; https://stackoverflow.com/questions/2031109/understanding-set-getsockopt-so-sndbuf-size-doubles





SO_SNDBUF, SO_RCVBUF 관련해서 코드로 테스트를 한 번 해볼까요? ^^ 역시 이번에도 기반 코드는 지난번의 것과 동일합니다.

두 가지 중에 검증하기 까다로운 SO_RCVBUF 먼저 테스트해보겠습니다.

연결 후, 클라이언트에서 서버로 넉넉잡고 10MB(10,485,760 bytes)를 전송하면 (서버 측 코드는 recv를 호출하지 않으므로) Receive Window가 꽉 차는 현상이 발생합니다. 이런 상태로 서버에서 10,485,760 바이트씩 수신처리를 하면 (당연히 한 번에 받아지지는 않지만) 제가 테스트한 환경에서는 일정하게 한 번의 recv 호출마다 195,640 바이트씩 반환이 됐습니다. 그리고 이때의 수신 측의 Receive Window Size를 보면 131,328이 나옵니다.

// 테스트 환경: Windows 10
5 28.991742 ..server_ip... ..client_ip... TCP 60 15000 → 21256 [ACK] Seq=1 Ack=4381 Win=131328 Len=0

이어서 수신 측의 SO_RCVBUF를 차례로 32,768과 0으로 지정해 각각 테스트해 보니 다음과 같은 일정한 패턴이 나옵니다.

RecvBufferSize: 65536인 경우, recv 호출에 반환한 크기 195,640 (근사값: 65536 + Receive Window Size)
RecvBufferSize: 32768인 경우, recv 호출에 반환한 크기 163,520 (근사값: 32768 + Receive Window Size)
RecvBufferSize:     0인 경우, recv 호출에 반환한 크기 131,400 (근사값:     0 + Receive Window Size)

그러니까, SO_RCVBUF와 Receive Window Size가 합쳐진 값이 해당 소켓을 위해 할당된 커널 측의 내부 수신 버퍼 크기라고 예상할 수 있습니다.

참고로, 위의 테스트는 연결 이후 초기에 나오는 값이 정확하고, 이어서 recv가 진행되면 "Receive Window Auto-Tuning feature" 때문에 크기가 변하는 현상이 나옵니다. 따라서 이와 관련한 테스트를 할 때는 아예 해당 기능을 끄고 하는 것도 좋을 것입니다.

C:\temp> netsh interface tcp show global
Querying active state...

TCP Global Parameters
----------------------------------------------
Receive-Side Scaling State          : enabled
Receive Window Auto-Tuning Level    : normal
Add-On Congestion Control Provider  : default
ECN Capability                      : disabled
RFC 1323 Timestamps                 : disabled
Initial RTO                         : 1000
Receive Segment Coalescing State    : enabled
Non Sack Rtt Resiliency             : disabled
Max SYN Retransmissions             : 4
Fast Open                           : enabled
Fast Open Fallback                  : enabled
HyStart                             : enabled
Proportional Rate Reduction         : enabled
Pacing Profile                      : off

// 끄는 방법
C:\temp> netsh int tcp set global autotuninglevel=disabled

// 켜는 방법
C:\temp> netsh int tcp set global autotuninglevel=normal




그럼 SO_SNDBUF는 어떻게 테스트할 수 있을까요?

이론적으로 알고 있는 내용에 따라,

Design issues - Sending small data segments over TCP with Winsock
; https://learn.microsoft.com/en-us/troubleshoot/windows/win32/data-segment-tcp-winsock

the send completion in the application only indicates the data buffer in an application send call is copied to the Winsock kernel buffer and doesn't indicate that the data has hit the network medium. The only exception is when you disable the Winsock buffering by setting SO_SNDBUF to 0


send 함수는 사용자 데이터를 커널 내 송신 버퍼로 복사하고 만약 버퍼에 다 못 담으면 blocking이 됩니다. 따라서 Socket.SendBufferSize의 기본 출력값이 65536이므로, 그렇다면 연결 후 수신 측의 VM을 pause 상태로 두고 send(65536 + 1)을 하면 blocking이 되어야 할 것입니다.

하지만, 이 테스트에는 한 가지 문제가 있습니다. 관련해서 아래의 Q&A가 있는데요,

What is the size of a socket send buffer in Windows?
; https://stackoverflow.com/questions/28785626/what-is-the-size-of-a-socket-send-buffer-in-windows

정리하면 "Remain(SO_SNDBUF) != 0"인 경우, 해당 호출에 1GB를 send 함수에 넘겨도 블록킹을 하지 않습니다. (이건 윈도우의 버퍼링 정책인 듯하고 다른 운영체제에서는 다르게 동작할 수 있습니다.) 따라서, send(65536 + 1)로 blocking 테스트를 하면 안 되고, 다음과 같이 send(65536) + send(1) 씩 전송을 해야 블록킹 현상을 재현할 수 있습니다.

int length = client.SendBufferSize; // Windows 11의 경우 보통 65536

byte[] buf = new byte[length];
sendLen = client.Send(buf, 0, buf.Length, SocketFlags.None); // 메서드 호출 후 곧바로 반환

buf = new byte[1];
sendLen = client.Send(buf, 0, buf.Length, SocketFlags.None); // 호출에서 blocking (수신 측의 VM을 pause 했고, 송신 버퍼가 꽉 찼으므로!)

확인을 위해, 첫 번째 호출의 버퍼 크기를 -1 시켜 send(65535) + send(1) 씩 전송을 하면 두 번 째 호출에서 블록킹이 안 걸리는 것을 확인할 수 있습니다. 테스트가 아주 깔끔하군요. ^^




참고로, SO_RCVBUF와 Receive Window, Send Window, Congestion Window에 대한 관계는 다음의 글에서 잘 정리하고 있습니다.

Understanding Throughput and TCP Windows
; http://packetbomb.com/understanding-throughput-and-tcp-windows/

[오리뎅이의 TCP 이야기 - 4] Window Scaling 옵션은 이젠 선택이 아닌 필수외다 
; https://blog.naver.com/goduck2/221113532619




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/11/2023]

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

비밀번호

댓글 작성자
 



2021-05-15 11시33분
정성태
2021-11-11 04시19분
[안녕하세요] 안녕하세요!
우선 좋은 글 감사드립니다.
제가 현재 c#을 통해 tcp 통신을 개발중인데 궁금한 것이 생겨 여쭤보고 싶습니다.

코드를 기준으로 말씀을 드리겠습니다.

서버는 제가 개발해 데이터를 보내는 것이 아니라 시중에 있는 것을 활용하고 있는데 해당 서버에서 카메라의 데이터를 tcp를 통해 보내줍니다.

저는 코드를 통해 tcp 소켓으로 네트워크를 개설 하였습니다.

그 후 임의의 byte[] recieveBuffer = new byte[100000]정도의 크기로 사용자 버퍼를 생성하여
socket.Receive(recieveBuffer)를 통해 사용자 버퍼에 통신 데이터를 저장 했습니다.

이 후 tcpSocket.Available를 호출해 크기를 비교했을 때 Available은 65536/ receiveBuffer에 훨씬 더 큰 값(ex. 3269328)이 저장 된 것을 확인했습니다.

Available의 경우 커널 버퍼의 수신가능 값을 호출해 주는 것으로 확인했는데 사용자 버퍼인 receiveBuffer 이렇게 큰 사이즈의 데이터를 수신할 수 있는 것인가요..?

제 생각에는 avilable 이상의 크기는 저장할 수 없을 것 같은데 결과를 보고 납득하지 못해 여쭤보고 싶습니다.

커널버퍼 보다 큰 데이터가 사용자 버퍼에 저장이 될 수 있는 것일까요??

된다면 이유가 무엇일까요??
[guest]
2021-11-11 04시50분
질문의 의도를 잘 이해하지 못하겠습니다. 그러니까, Available로 3_269_328을 반환하는 상태에서 (크기가 100_000인 receiveBuffer로) socket.Receive(receiveBuffer)를 호출했더니 receiveBuffer에 3_269_328 바이트가 담겨져 반환되었다는 것인가요?
정성태

... 106  107  108  109  110  111  112  113  114  115  116  117  118  [119]  120  ...
NoWriterDateCnt.TitleFile(s)
10949정성태4/28/201619884.NET Framework: 575. SharedDomain과 JIT 컴파일파일 다운로드1
10948정성태4/28/201623827.NET Framework: 574. .NET - 눈으로 확인하는 SharedDomain의 동작 방식 [3]파일 다운로드1
10947정성태4/27/201621706.NET Framework: 573. .NET CLR4 보안 모델 - 4. CLR4 보안 모델에서의 조건부 APTCA 역할파일 다운로드1
10946정성태4/26/201624518VS.NET IDE: 106. Visual Studio 2015 확장 - INI 파일을 위한 사용자 정의 포맷 기능 (Syntax Highlighting)파일 다운로드1
10945정성태4/26/201618285오류 유형: 327. VSIX 프로젝트 빌드 시 The "VsTemplatePaths" task could not be loaded from the assembly 오류 발생
10944정성태4/22/201619519디버깅 기술: 80. windbg - 풀 덤프 파일로부터 텍스트 파일의 내용을 찾는 방법
10943정성태4/22/201624377디버깅 기술: 79. windbg - 풀 덤프 파일로부터 .NET DLL을 추출/저장하는 방법 [1]
10942정성태4/19/201619680디버깅 기술: 78. windbg 사례 - .NET 예외가 발생한 시점의 오류 분석 [1]
10941정성태4/19/201619588오류 유형: 326. Error MSB8020 - The build tools for v120_xp (Platform Toolset = 'v120_xp') cannot be found.
10940정성태4/18/201622861Windows: 116. 프로세스 풀 덤프 시간을 줄여 주는 Process Reflection [3]
10939정성태4/18/201623886.NET Framework: 572. .NET APM 비동기 호출의 Begin...과 End... 조합 [3]파일 다운로드1
10938정성태4/13/201623452오류 유형: 325. 파일 삭제 시 오류 - Error 0x80070091: The directory is not empty.
10937정성태4/13/201631674Windows: 115. UEFI 모드로 윈도우 10 설치 가능한 USB 디스크 만드는 방법
10936정성태4/8/201642361Windows: 114. 삼성 센스 크로노스 7 노트북의 운영체제를 USB 디스크로 새로 설치하는 방법 [3]
10935정성태4/7/201626656웹: 32. Edge에서 Google Docs 문서 편집 시 한영 전환키가 동작 안하는 문제
10934정성태4/5/201625380디버깅 기술: 77. windbg의 콜스택 함수 인자를 쉽게 확인하는 방법 [1]
10933정성태4/5/201630994.NET Framework: 571. C# - 스레드 선호도(Thread Affinity) 지정하는 방법 [8]파일 다운로드1
10932정성태4/4/201623284VC++: 96. C/C++ 식 평가 - printf("%d %d %d\n", a, a++, a);
10931정성태3/31/201623559개발 환경 구성: 283. Hyper-V 내에 구성한 Active Directory 환경의 시간 구성 방법 [3]
10930정성태3/30/201621514.NET Framework: 570. .NET 4.5부터 추가된 CLR Profiler의 실행 시 Rejit 기능
10929정성태3/29/201631627.NET Framework: 569. ServicePointManager.DefaultConnectionLimit의 역할파일 다운로드1
10928정성태3/28/201637339.NET Framework: 568. ODP.NET의 완전한 닷넷 버전 Oracle ODP.NET, Managed Driver [2]파일 다운로드1
10927정성태3/25/201626547.NET Framework: 567. System.Net.ServicePointManager의 DefaultConnectionLimit 속성 설명
10926정성태3/24/201626087.NET Framework: 566. openssl의 PKCS#1 PEM 개인키 파일을 .NET RSACryptoServiceProvider에서 사용하는 방법 [10]파일 다운로드1
10925정성태3/24/201620387.NET Framework: 565. C# - Rabin-Miller 소수 생성 방법을 이용하여 RSACryptoServiceProvider의 개인키를 직접 채워보자 - 두 번째 이야기파일 다운로드1
10924정성태3/22/201621042오류 유형: 324. Visual Studio에서 Azure 클라우드 서비스 생성 시 Failed to initialize the PowerShell host 에러 발생
... 106  107  108  109  110  111  112  113  114  115  116  117  118  [119]  120  ...