소켓 옵션 관련 함수
이번 포스트에선 소켓의 옵션을 변경하거나 현재 소켓의 설정 정보를 가져오는 방법에 대해서 알아보자.
header : #include <sys/types.h>
#include <sys/socket.h>
int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *potlen)
> 소켓의 정보를 가져오는 함수
인자 설명
- int sockfd : 소켓의 디스크립터
- int level : 검사할 프로토콜 레벨
- int optname : 옵션 정보를 가져 올 옵션의 이름
- void *optval : 옵션 값이 저장될 버퍼를 가르키는 주소
- socklen_t *optlen : 입력된 버퍼의 길이 전달
∗ 많이 사용되는 프로토콜 레벨과 옵션의 이름
프로토콜 레벨 | 옵션 이름 | 의미 |
SOL_SOCKET | SO_REUSEADDR | 이미 사용되고 있는 주소에 소켓을 연결 할 수 있도록 설정 |
SOL_SOCKET | SO_KEEPALIVE | 소켓 연결에 연결을 유지하는 패킷을 전송하도록 설정 |
SOL_SOCKET | SO_SNDBUF | 송신 버퍼의 크기 |
SOL_SOCKET | SO_RCVBUF | 수신 버퍼의 크기 |
SOL_SOCKET | SO_TYPE | 소켓의 형태 |
getsockopt()를 이용한 송수신 버퍼의 크기를 가져오는 소스 코드
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main(void) { int sock; unsigned int sendsize = 0; unsigned int recvsize = 0; unsigned int optlen; if ((sock = socket(AF_INET,SOCK_STREAM,0)) < 0){ perror("socket "); return 1; } optlen = sizeof(sendsize); getsockopt(sock, SOL_SOCKET,SO_SNDBUF,(char*)&sendsize, &optlen); optlen = sizeof(recvsize); getsockopt(sock, SOL_SOCKET,SO_RCVBUF,(char*)&recvsize, &optlen); printf("sendsize: %u\n",sendsize); printf("recive: %u\n",recvsize); close(sock); return 0; }
출력
sendsize: 16384 recive: 87380 Press <RETURN> to close this window...
∗ 송수신 버퍼의 크기를 가져오기 위해 옵션 이름은 SO_SENDBUF, SO_RCVBUF를 사용했으며,
프로토콜 레벨 명은 SOL_SOCKET을 사용하였다.
header : #include <sys/types.h>
#include <sys/socket.h>
int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t *potlen)
> 소켓의 설정을 변경하는 함수
인자 설명
- int sockfd : 소켓의 디스크립터
- int level : 검사할 프로토콜 레벨
- int optname : 옵션 정보를 가져 올 옵션의 이름
- const void *optval : 변경할 옵션이 저장된 위치의 주소 값
- socklen_t *optlen : 변경할 옵션의 길이
setsockopt()의 사용 소스 코드
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main(void) { int sock; unsigned int sendsize = 0; unsigned int optlen; if((sock=socket(AF_INET, SOCK_STREAM, 0)) < 0){ perror("socket "); return 1; } optlen = sizeof(sendsize); getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&sendsize, &optlen); printf("sendsize: %u\n",sendsize); sendsize = 100; optlen = sizeof(sendsize); setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&sendsize, optlen); getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&sendsize, &optlen); printf("sendsize: %u\n",sendsize); close(sock); return 0; }
출력
sendsize: 16384 sendsize: 4608 Press <RETURN> to close this window...
setsockopt()함수를 통해 송신 버퍼의 크기를 변경하고,
변경 전과 후의 getsockopt()함수를 이용해 송신 버퍼의 크기를 출력하고 있다.