int CoreSocket::connect(const GSockAddr &server, int iFLTag, int *fd, int nodelay) { int type = SOCK_STREAM; int ret; *fd = ::socket(server.family(), type, 0); if (*fd == -1) return LS_FAIL; if (iFLTag) ::fcntl(*fd, F_SETFL, iFLTag); if ((nodelay) && ((server.family() == AF_INET) || (server.family() == AF_INET6))) ::setsockopt(*fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(int)); ret = ::connect(*fd, server.get(), server.len()); if (ret != 0) { if (!((iFLTag & O_NONBLOCK) && (errno == EINPROGRESS))) { ::close(*fd); *fd = -1; } return LS_FAIL; } return ret; }
int CoreSocket::bind(const GSockAddr &server, int type, int *fd) { int ret; if (!server.get()) return EINVAL; *fd = ::socket(server.family(), type, 0); if (*fd == -1) return errno; int flag = 1; if (setsockopt(*fd, SOL_SOCKET, SO_REUSEADDR, (char *)(&flag), sizeof(flag)) == 0) { ret = ::bind(*fd, server.get(), server.len()); if (!ret) return ret; } ret = errno; ::close(*fd); *fd = -1; return ret; }
int CoreSocket::listen(const GSockAddr &server, int backLog, int *fd, int sndBuf, int rcvBuf) { int ret; ret = bind(server, SOCK_STREAM, fd); if (ret) return ret; if (sndBuf > 4096) ::setsockopt(*fd, SOL_SOCKET, SO_SNDBUF, &sndBuf, sizeof(int)); if (rcvBuf > 4096) ::setsockopt(*fd, SOL_SOCKET, SO_RCVBUF, &rcvBuf, sizeof(int)); if (((server.family() == AF_INET) || (server.family() == AF_INET6))) { int nodelay = 1; ::setsockopt(*fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(int)); #ifdef TCP_FASTOPEN nodelay = backLog / 2; if (nodelay > 256) nodelay = 256; ::setsockopt(*fd, IPPROTO_TCP, TCP_FASTOPEN, &nodelay, sizeof(int)); #endif } ret = ::listen(*fd, backLog); if (ret == 0) return 0; ret = errno; ::close(*fd); *fd = -1; return ret; }