Network socket
네트워크 소켓(network socket)은 컴퓨터 네트워크를 경유하는 프로세스 간 통신의 종착점이다. 오늘날 컴퓨터 간 통신의 대부분은 인터넷 프로토콜을 기반으로 하고 있으므로, 대부분의 네트워크 소켓은 인터넷 소켓이다. 네트워크 통신을 위한 프로그램들은 소켓을 생성하고, 이 소켓을 통해서 서로 데이터를 교환한다. 소켓은 RFC 147 에 기술사항이 정의되어 있다.
인터넷 소켓은 다음과 같은 요소들로 구성되어 있다.
- 인터넷 프로토콜 (TCP, UDP, raw IP)
- 로컬 IP 주소
- 로컬 포트
- 원격 IP 주소
- 원격 포트
인터넷 소켓은 크게 두 개의 타입으로 분류할 수 있다.
- UDP 프로토콜을 사용하는 경우.
- TCP 프로토콜을 사용하는 경우.
일반적으로 소켓 프로그래밍(네트워크 프로그래밍)은 이 것을 지칭한다.
Category
- Berkeley sockets
- Winsock (Windows sockets)
- C:sockaddr_in (sockaddr_in와 동일)
- C:socket
- C:bind
- C:listen
- C:setsockopt
- C:send
- C:recv
- C:shutdown
- Maximum transmission unit (MTU)
- Maximum segment size (MSS)
- Nagle
- Python:socket (Python)
- C standard library - 소켓관련 함수 목록 있음.
Documentation
- RFC 147
서버와 클라이언트의 연결과 데이터 통신 흐름
Socket_-_server_and_client_flow.png
Win32 소켓프로그래밍 강좌
Download: Tipssoft_com-socket_programming.zip
- TCP/IP의 역사
- ISO의 OSI 참조모델
- TCP/IP 의 주소 체계
- Client / Server 모델
- 채팅 프로그램 만들기(Server) Step 1
- 채팅 프로그램 만들기(Server) Step 2
- 채팅 프로그램 만들기(Server)
send & recv byte size
send로 보낸 데이터 크기와 recv로 받은 데이터 크기는 서로 다르다. 자세한 내용은 아래 참조.
Streamed sockets:
The sockets are generally used in a streamed way: you'll receive all the data sent, but not necessarily all at once. You may as well receive pieces of data. Your approach of sending the length is hence valid: once you've received the length, you cann then load a buffer, if needed accross successive reads, until you got everything that you expected. So you have to loop on receives, and define a strategy on how to ahandle extra bytes received. |
Datagramme (packet oriented) sockets:
If your application is really packet oriented, you may consider to create a datagramme socket, by requesting linux or windows socket(), the SOCK_DGRAM, or better SOCK_SEQPACKET socket type. |
Risk with your binary size data:
Be aware that the way you send and receive your size data appers to be assymetric. You have hence a major risk if the sending and receiving between machine with CPU/architectures that do not use the same endian-ness. You can find here some hints on how to ame your code platform/endian-independent. |
TCP vs UDP
TCP:
- 커넥션 기반
- 안정성과 순서를 보장한다
- 패킷을 자동으로 쪼개준다
- 적당한 속도로 보내준다. (회선이 처리할 수 있을 만큼)
- 파일을 쓰는 것처럼 사용하기 쉽다
UDP:
- 커넥션 기반이 아니다. 직접 구현해야 한다
- 안정적이지 않고 순서도 보장되지 않는다. 데이터를 잃을 수도, 중복될 수도 있다.
- 데이터가 크다면, 보낼 때 직접 패킷 단위로 잘라야 한다.
- 회선이 처리할 수 있을만큼 나눠서 보내야 한다.
- 패킷을 잃었을 경우, 필요하다면 다양한 방법으로 이를 찾아내서 다시 보내야 한다.
- 데이터가 전송될 수도 안될 수도 있지만, UDP가 보장해주는 건 데이터의 '양'이다. 한 쪽에서 256바이트를 보냈으면, 받는 쪽에서도 무조건 256바이트를 받는다. 처음 100바이트를 받을 수는 없다.
TIME_WAIT
- [추천] TIME_WAIT 상태란 무엇인가 1
- [추천] TCP의 TIME_WAIT를 없애는 법 2
#SO_REUSEADDR 옵션을 설정하면 된다.
Socket options
SO_LINGER
다음은 SO_LINGER 옵션에 사용되는 데이터 구조체입니다.
-
l_onoff
: Linger 옵션을 활성화 할것인지 비 활성화 할것인지에 대한 플래그 -
l_linger
: Linger 옵션이 활성화 되었을 때 기다리는 시간
위 두개의 멤버변수의 값에 따라 다음 세 가지 close 방식이 결정되어집니다.
-
l_onoff == 0
: 이것은 Linger를 비활성화 하겠다는 것으로 소켓의 default 값이다. 소켓버퍼에 남아있는 모든 데이터를 전송하는 일반적인 소켓의 정상 종료가 이루어집니다. -
l_onoff > 0
이고l_linger == 0
: close가 즉시 리턴을 해서 상태가 종료 되고 소켓 버퍼에 남아있는 데이터를 버리는 비정상 종료가 이루어집니다. 만약 TCP 연결 상태일 경우에는 상대편 호스트에 리셋을 위한 RST 패킷을 보냅니다. -
l_onoff > 0
이고l_linger > 0
: 지정한 시간동안 대기하고 버퍼에 남아있는 데이터를 모두 보냅니다. 지정된 시간 내에 데이터를 모두 보냈다면 정상적으로 리턴이 되고 시간이 초과되었다면 에러와 함께 리턴이 되는 방식으로 특정 조건에 따라 비정상 종료 혹은 정상 종료가 이루어집니다.
SO_REUSEADDR
Python example:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# ...
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
소켓 소유권 이전
- Stackoverflow - Sending file descriptor by Linux socket
- Stackoverflow - Transfer ownership of unix domain sockets from one process to other
- Stackoverflow - Passing socket descriptor between two processes using shared memory
See also
Favorite site
- Wikipedia (en) Network socket
- libsocket 0.8.0: Links
- KLDP 리눅스의 GCC를 사용한 소켓 프로그래밍 3
- Joinc: BSD 소켓 프로그래밍 입문 4
Library
Guide
- TCP 접속 제한 풀기 ( 포트 번호 제한 풀기)
- 리눅스 소켓 접속 수 제한 풀기
- 우분투 소켓 접속 제한 풀어 소켓 갯수 늘리기(How to increase maximum socket connection in Ubuntu?)
- 소켓 코딩시 실제적으로 주의해야할 사항 5
- [추천] CLOSE_WAIT & TIME_WAIT 최종 분석 6
Topic
- Stackoverflow: IPC performance: Named Pipe vs Socket
- Pipe vs Unix Socket Performance (Pipe가 Socker보다 빠르다)
References
-
TIME_WAIT_-_The_Missing_Papers.pdf ↩
-
Sunyzero.tistory.com_-_Remove_TCP_TIME_WAIT.pdf ↩
-
Wiki.kldp.org-socket_programming.zip ↩
-
Joinc_-BSD_Socket_Programming-_beginning.pdf ↩
-
Depiness_-_socket_codeing_warning.pdf ↩
-
Tech.kakao.com_-_closewait-timewait.pdf ↩
-
Things_to_consider_when_using_UDP_-Meetup-_TOAST_Cloud.pdf ↩
-
Kernel_Parameter_Decisions_for_TCP_Network_Performance_on_Linux_Servers_-Part_1-Meetup-_TOAST_Cloud.pdf ↩
-
Kernel_Parameter_Decisions_for_TCP_Network_Performance_on_Linux_Servers_-Part_2-Meetup-_TOAST_Cloud.pdf ↩
-
Kernel_Parameter_Decisions_for_TCP_Network_Performance_on_Linux_Servers_-Part_3-Meetup-_TOAST_Cloud.pdf ↩
-
Onlamp.com_-_tcp_tuning.pdf ↩