blog
April 18, 2022
fd_set, FD_SET, FD_ZERO에 대하여
typedef struct
{
__fd_mask fds_bits[__FD_SETSIZE / __NFDBITS];
} fd_set;
fd_set rfds;
FD_ZERO(&rfds);
int fd_socket = socket(AF_INET, SOCK_STREAM, 0);
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd_socket, &rfds);
int fd_socket = socket(AF_INET, SOCK_STREAM, 0);
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd_socket, &rfds);
// 사용
FD_CLR(fd_socket, &rfds); // 추가
close(fd_socket); // 추가
int fd_socket = socket(AF_INET, SOCK_STREAM, 0);
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd_socket, &rfds);
FD_ISSET(fd_socket, &rfds); // 추가, 1 반환
// 사용
FD_CLR(fd_socket, &rfds);
FD_ISSET(fd_socket, &rfds); // 추가, 0 반환
close(fd_socket);
// 프로토타입
int socket(int domain, int type, int protocol);
// 예시
int socket = socket(PF_INET, SOCK_STREAM, 0);
// 프로토타입
int bind(int socket, const struct sockaddr *address, socklen_t address_len);
// 예시
if (bind(socket, (struct sockaddr*) &socket_address, sizeof(socket_address)) == -1)
// error
struct sockaddr {
__uint8_t sa_len; /* total length */
sa_family_t sa_family; /* [XSI] address family */
char sa_data[14]; /* [XSI] addr value (actually larger) */
};
struct sockaddr_in {
__uint8_t sin_len;
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
Why is the address length parameter neccessary when binding a socket in C?
// 프로토타입
int listen(int socket, int backlog);
// 예시
if (listen(socket, 5) == -1)
// error
// 프로토타입
int accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len);
// 예시
int client_socket = accept(server_socket, (struct sockaddr*) &client_address, &clientAddress_size);
if (client_socket == -1)
// error
TCP Socket - Blocking / Non-Blocking
fcntl(sock_fd, F_SETFL, flag | O_NONBLOCK);
Fork, Thread 그리고 Asynchronous
uint16_t htons(uint16_t hostshort);
uint32_t htonl(uint32_t hostlong);
uint16_t ntohs(uint16_t netshort);
uint32_t ntohl(uint32_t netlong);
in_addr_t inet_addr(const char *cp);
// fd_set
typedef struct fd_set {
__int32_t fds_bits[__DARWIN_howmany(__DARWIN_FD_SETSIZE, __DARWIN_NFDBITS)];
} fd_set;
// 프로토타입
int select(int nfds,
fd_set *restrict readfds,
fd_set *restrict writefds,
fd_set *restrict errorfds,
struct timeval *restrict timeout);
// 프로토타입
int poll(struct pollfd fds[], nfds_t nfds, int timeout);
// 프로토타입
int kqueue(void);
int kevent(int kq, const struct kevent *changelist, int nchanges, struct kevent *eventlist, int nevents, const struct timespec *timeout);