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 바이트가 담겨져 반환되었다는 것인가요?
정성태

1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13421정성태10/4/20233238닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235264스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233088스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233749닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233332닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233150오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233637닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233388디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233580닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236846닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233361Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20234858닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233718닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233714Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233471닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233408VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233835닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233356오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233186오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233243닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/20233505닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/20233341오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
13399정성태8/9/20233369닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
13398정성태8/3/20234122스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/20233635닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233333스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...