// dbss作为服务端 // 初始化服务器端socket void init_server() { int fd; struct sockaddr_in addr; memset(&addr, 0, sizeof addr); fd = socket(AF_INET, SOCK_STREAM, 0); if(fd < 0) { printf("Failed to init server socket, %s, %s, %d\n", __FUNCTION__, __FILE__, __LINE__); exit(EXIT_FAILURE); } set_reuse_addr(fd); addr.sin_family = AF_INET; addr.sin_port = htons(lsn_port); inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr); if(bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { #ifdef DEBUG_STDOUT printf("Failed to bind, %s, %s, %d\n", __FUNCTION__, __FILE__, __LINE__); #else #endif close(fd); exit(EXIT_FAILURE); } if(listen(fd, DESCRIPTOR_MAX) < 0) { #ifdef DEBUG_STDOUT printf("Failed to listen, %s, %s, %d\n", __FUNCTION__, __FILE__, __LINE__); #else #endif close(fd); exit(EXIT_FAILURE); } if(sockinfo[fd].fd == 0) { sockinfo[fd].fd = fd; sockinfo[fd].type = TYPE_LISTEN; } epoll_addfd(efd, fd, EPOLLIN); }
socket_t tcp_create(unsigned int ip, unsigned short port) { /*create socket*/ int sock = ::socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { return -1; //initial socket error } /*set reuse address*/ if(set_reuse_addr(sock) != 0){ ::close(sock); return -1; } /*set local address*/ struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = ::htons(port); addr.sin_addr.s_addr = htonl(ip); /*bind socket to local address*/ if (::bind(sock, (struct sockaddr *) &addr, sizeof(addr)) != 0){ ::close(sock); return -1; } return sock; }
bool XSocket::listen(const XSockAddr& addr, int backlog) { if (m_sock == INVALID_SOCKET) return false; if (backlog < 0) backlog = 0X7FFFFFFF; if (!set_reuse_addr(true)) return false; if (!this->bind(addr)) return false; if (0 != ::listen(m_sock, backlog)) return false; return true; }
static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist) { struct sockaddr_in sin; int sockfd; long flags; memset(&sin, 0, sizeof sin); sin.sin_family = AF_INET; sin.sin_port = htons(listen_port); if (listen_addr) { /* Well, host better be an IP address here. */ if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0) return 0; } else { sin.sin_addr.s_addr = htonl(INADDR_ANY); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) return 0; if (set_reuse_addr(sockfd)) { logerror("Could not set SO_REUSEADDR: %s", strerror(errno)); close(sockfd); return 0; } set_keep_alive(sockfd); if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) { logerror("Could not bind to %s: %s", ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)), strerror(errno)); close(sockfd); return 0; } if (listen(sockfd, 5) < 0) { logerror("Could not listen to %s: %s", ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)), strerror(errno)); close(sockfd); return 0; } flags = fcntl(sockfd, F_GETFD, 0); if (flags >= 0) fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC); ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc); socklist->list[socklist->nr++] = sockfd; return 1; }
static int setup_multicast_impl(char * bindAddr, unsigned int nTTL, char * p_multicast_addr, char * p_port, struct mcast_connection * p_mcast_conn) { int rc; debug_outputln("%s %4.4u : %s %s %s %3.3u", __FILE__, __LINE__, bindAddr, p_multicast_addr, p_port, nTTL); p_mcast_conn->multiAddr_ = ResolveAddressWithFlags(p_multicast_addr, p_port, AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, AI_PASSIVE); if (NULL == p_mcast_conn->multiAddr_) { debug_outputln("%s %4.4u : %10.10d %8.8x", __FILE__, __LINE__, WSAGetLastError(), WSAGetLastError()); goto cleanup; } dump_addrinfo(p_mcast_conn->multiAddr_, __FILE__, __LINE__); // Resolve the binding address p_mcast_conn->bindAddr_ = ResolveAddressWithFlags(bindAddr, p_port, p_mcast_conn->multiAddr_->ai_family, p_mcast_conn->multiAddr_->ai_socktype, p_mcast_conn->multiAddr_->ai_protocol, AI_PASSIVE); if (NULL == p_mcast_conn->bindAddr_) { debug_outputln("%s %4.4u : %10.10d %8.8x", __FILE__, __LINE__, WSAGetLastError(), WSAGetLastError()); goto cleanup; } dump_addrinfo(p_mcast_conn->bindAddr_, __FILE__, __LINE__); // // Create the socket. In Winsock 1 you don't need any special // flags to indicate multicasting. // p_mcast_conn->socket_ = socket(p_mcast_conn->multiAddr_->ai_family, p_mcast_conn->multiAddr_->ai_socktype, p_mcast_conn->multiAddr_->ai_protocol); if (p_mcast_conn->socket_ == INVALID_SOCKET) { debug_outputln("%s %4.4u : %10.10d %8.8x", __FILE__, __LINE__, WSAGetLastError(), WSAGetLastError()); goto cleanup; } if (!set_reuse_addr(p_mcast_conn->socket_)) { debug_outputln("%s %4.4u : %10.10d %8.8x", __FILE__, __LINE__, WSAGetLastError(), WSAGetLastError()); goto cleanup; } // Join the multicast group if specified rc = join_mcast_group_set_ttl(p_mcast_conn->socket_, p_mcast_conn->multiAddr_, p_mcast_conn->bindAddr_, nTTL); if (rc == SOCKET_ERROR) { debug_outputln("%s %4.4u : %10.10d %8.8x", __FILE__, __LINE__, WSAGetLastError(), WSAGetLastError()); goto cleanup; } dump_locally_bound_socket(p_mcast_conn->socket_, __FILE__, __LINE__); return 1; cleanup: return 0; }
static int socksetup(char *listen_addr, int listen_port, int **socklist_p) { struct sockaddr_in sin; int sockfd; long flags; memset(&sin, 0, sizeof sin); sin.sin_family = AF_INET; sin.sin_port = htons(listen_port); if (listen_addr) { /* Well, host better be an IP address here. */ if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0) return 0; } else { sin.sin_addr.s_addr = htonl(INADDR_ANY); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) return 0; if (set_reuse_addr(sockfd)) { close(sockfd); return 0; } if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) { close(sockfd); return 0; } if (listen(sockfd, 5) < 0) { close(sockfd); return 0; } flags = fcntl(sockfd, F_GETFD, 0); if (flags >= 0) fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC); *socklist_p = xmalloc(sizeof(int)); **socklist_p = sockfd; return 1; }
//----------------------------------------------------------------------------- bool CySocket::listen(int port, int max_connections) { if (sock == INVALID_SOCKET) return false; // set sockaddr for listening sockaddr_in sai; memset(&sai, 0, sizeof(sai)); sai.sin_family = AF_INET; // Protocol sai.sin_addr.s_addr = htonl(INADDR_ANY); // No Filter sai.sin_port = htons(port); // Listening Port set_reuse_port(); // Re-Use Port set_reuse_addr(); // Re-Use IP if (bind(sock, (sockaddr *) &sai, sizeof(sockaddr_in)) != SOCKET_ERROR) if (::listen(sock, max_connections) == 0) return true; return false; }
tcp_server_t *tcp_server_create(int port, int max_conn) { tcp_server_t *server = NULL; tcp_server_stream_t *stream = NULL; int max_conn_count = TCP_MAX_STREAM_NUM; int i = 0; struct sockaddr_in server_addr; struct epoll_event event; server = (tcp_server_t *)malloc(sizeof(tcp_server_t)); if (NULL == server) { goto error; } bzero(server, sizeof(tcp_server_t)); server->rcv_cb = rcv_cb_default; server->snd_cb = snd_cb_default; server->port = port; if (max_conn > 0) { max_conn_count = max_conn; } /* 创建并发连接结构 */ server->streams = (tcp_server_stream_t *)malloc(sizeof(tcp_server_stream_t) * max_conn_count); if (NULL == server->streams) { log_error("malloc for server->streams failed."); goto error; } bzero(server->streams, sizeof(tcp_server_stream_t) * max_conn_count); server->stream_num = max_conn_count; /* idle stream链表初始化 */ for (i = 0; i < max_conn_count; i++) { server->streams[i].index = i; add_stream_into_idle_list(server, &server->streams[i]); } /* 创建listen socket */ server->listen_fd = socket(AF_INET, SOCK_STREAM, 0); if (-1 == server->listen_fd) { log_error("create socket failed, %s", strerror(errno)); goto error; } /* 设置为非阻塞 */ if (!set_non_blocking(server->listen_fd)){ log_error("set_non_blocking failed."); goto error; } /* 设置地址重用 */ if (!set_reuse_addr(server->listen_fd)) { log_error("set reuse addr failed."); goto error; } /* 绑定端口 */ bzero(&server_addr, sizeof(struct sockaddr_in)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(server->port); if (bind(server->listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { log_error("bind server addr failed, %s", strerror(errno)); goto error; } /* 设置监听 */ if (listen(server->listen_fd, TCP_MAX_LISTEN_NUM) < 0) { log_error("listen failed, %s", strerror(errno)); goto error; } /* 创建epoll句柄 */ server->epoll_fd = epoll_create(TCP_MAX_CONNECT_NUM); if (server->epoll_fd < 0) { log_error("epoll_create failed, %s", strerror(errno)); goto error; } /* 获取空闲的stream */ stream = get_idle_tcp_stream(server); if (NULL == stream) { log_error("get_idle_tcp_stream for listen stream failed."); goto error; } /* 将listen fd加入epoll */ bzero(&event, sizeof(event)); event.data.fd = server->listen_fd; event.data.ptr = stream; event.events = EPOLLIN | EPOLLET; /* 创建listen stream */ tcp_stream_init(server, stream, server->listen_fd, NULL); stream->snd_cb = NULL; stream->rcv_cb = accept_cb; add_stream_into_busy_list(server, stream); return server; error: tcp_server_destroy(server); return NULL; }
static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist) { int socknum = 0; int maxfd = -1; char pbuf[NI_MAXSERV]; struct addrinfo hints, *ai0, *ai; int gai; long flags; sprintf(pbuf, "%d", listen_port); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0); if (gai) { logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai)); return 0; } for (ai = ai0; ai; ai = ai->ai_next) { int sockfd; sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (sockfd < 0) continue; if (sockfd >= FD_SETSIZE) { logerror("Socket descriptor too large"); close(sockfd); continue; } #ifdef IPV6_V6ONLY if (ai->ai_family == AF_INET6) { int on = 1; setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)); /* Note: error is not fatal */ } #endif if (set_reuse_addr(sockfd)) { logerror("Could not set SO_REUSEADDR: %s", strerror(errno)); close(sockfd); continue; } if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) { logerror("Could not bind to %s: %s", ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen), strerror(errno)); close(sockfd); continue; /* not fatal */ } if (listen(sockfd, 5) < 0) { logerror("Could not listen to %s: %s", ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen), strerror(errno)); close(sockfd); continue; /* not fatal */ } flags = fcntl(sockfd, F_GETFD, 0); if (flags >= 0) fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC); ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc); socklist->list[socklist->nr++] = sockfd; socknum++; if (maxfd < sockfd) maxfd = sockfd; } freeaddrinfo(ai0); return socknum; }
int main(int argc, char* argv[]) { if ((argc != 2)) { printf("\tusage: ./server <packet_size>\n"); exit(1); } int packet_sz = atoi(argv[1]); printf("Packet size = %d\n", packet_sz); int listenfd; if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Create socket error"); exit(1); } set_reuse_addr(listenfd); struct sockaddr_in server_addr; bzero(&server_addr, sizeof server_addr); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(SERVER_PORT); if (bind(listenfd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr)) == -1) { perror("Bind error"); exit(1); } if (listen(listenfd, BACKLOG) == -1) { perror("Listen error"); exit(1); } struct sockaddr_in cli_addr; socklen_t cli_len = sizeof cli_addr; int connfd; if ((connfd = accept(listenfd, (struct sockaddr*)&cli_addr, &cli_len)) == -1) { perror("Accept error"); exit(1); } printf("Accept a new client.\n"); // mark the socket fd non-blocking //set_nonblocking(connfd); signal(SIGPIPE, SIG_IGN); // send the packet size packet_sz = htonl(packet_sz); assert(write(connfd, &packet_sz, sizeof(int)) == sizeof(int)); int sz_ack; assert(read(connfd, &sz_ack, sizeof(int)) == sizeof(int)); assert(sz_ack == packet_sz); const int BUF_SIZE = ntohl(packet_sz); char buf[MAX_BUF_SIZE]; int round_trip = 1000; int i; for (i = 0; i < round_trip; ++i) { int nread = 0; while (1) { int this_read = read(connfd, buf+nread, BUF_SIZE - nread); assert(this_read > 0); nread += this_read; if (nread == BUF_SIZE) { //printf("Finished %d round.\n", i); break; } } #ifndef NOACK char ack = 1; int nwrite = write(connfd, &ack, sizeof ack); assert(nwrite == 1); #endif } long total = BUF_SIZE * round_trip; printf("Recieved %ld bytes.\n", total); close(connfd); }
int main(int argc, char ** argv) { int result; fd_set read_fd; struct addrinfo * p_group_address; struct addrinfo * p_iface_address; struct addrinfo a_hints; memset(&a_hints, 0, sizeof(a_hints)); SOCKET s = socket(AF_INET, SOCK_DGRAM, 0); assert(s>=0); a_hints.ai_family = AF_INET; a_hints.ai_protocol = 0; a_hints.ai_socktype = SOCK_DGRAM; result = getaddrinfo(MCAST_GROUP_ADDRESS, MCAST_PORT_NUMBER, &a_hints, &p_group_address); assert(0 == result); dump_addrinfo(stderr, p_group_address); a_hints.ai_flags = AI_PASSIVE; result = getaddrinfo(INTEFACE_BIND_ADDRESS, MCAST_PORT_NUMBER, &a_hints, &p_iface_address); assert(0 == result); result = set_reuse_addr(s); assert(0 == result); dump_addrinfo(stderr, p_iface_address); result = join_mcast_group_set_ttl(s, p_group_address, p_iface_address, DEFAULT_TTL); assert(0 == result); { struct sigaction query_action; memset(&query_action, 0, sizeof(query_action)); query_action.sa_handler = &sigint_handle; if (sigaction (SIGINT, NULL, &query_action) < 0) exit(EXIT_FAILURE); /* sigaction returns -1 in case of error. */ } while (!g_stop_processing) { ssize_t bytes_read; struct sockaddr recv_from_data; socklen_t recv_from_length = sizeof(recv_from_data); struct timeval select_timeout = { 1, 0 }; FD_ZERO(&read_fd); FD_SET(s, &read_fd); result = select(s+1, &read_fd, NULL, NULL, &select_timeout); switch (result) { case -1: break; case 0: fprintf(stdout, "%4.4u %s : Timeout\n", __LINE__, __func__); break; default: if (FD_ISSET(s, &read_fd)) { bytes_read = recvfrom(s, &g_input_buffer[0], sizeof(g_input_buffer), 0, &recv_from_data, &recv_from_length); if (bytes_read >= 0) { fprintf(stdout, "%4.4u %s : %u %s %u %2.2hhx %2.2hhx..\n", __LINE__, __func__, bytes_read, inet_ntoa((((struct sockaddr_in *)&recv_from_data)->sin_addr)), ntohs((((struct sockaddr_in *)&recv_from_data)->sin_port)), g_input_buffer[0], g_input_buffer[1] ); } else { fprintf(stderr, "%4.4u %s : %d %s\n", __LINE__, __func__, errno, strerror(errno)); } } break; } } return 0; }
static int socksetup(char *listen_addr, int listen_port, int **socklist_p) { int socknum = 0, *socklist = NULL; int maxfd = -1; char pbuf[NI_MAXSERV]; struct addrinfo hints, *ai0, *ai; int gai; long flags; sprintf(pbuf, "%d", listen_port); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0); if (gai) die("getaddrinfo() failed: %s", gai_strerror(gai)); for (ai = ai0; ai; ai = ai->ai_next) { int sockfd; sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (sockfd < 0) continue; if (sockfd >= FD_SETSIZE) { logerror("Socket descriptor too large"); close(sockfd); continue; } #ifdef IPV6_V6ONLY if (ai->ai_family == AF_INET6) { int on = 1; setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)); /* Note: error is not fatal */ } #endif if (set_reuse_addr(sockfd)) { close(sockfd); continue; } if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) { close(sockfd); continue; /* not fatal */ } if (listen(sockfd, 5) < 0) { close(sockfd); continue; /* not fatal */ } flags = fcntl(sockfd, F_GETFD, 0); if (flags >= 0) fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC); socklist = xrealloc(socklist, sizeof(int) * (socknum + 1)); socklist[socknum++] = sockfd; if (maxfd < sockfd) maxfd = sockfd; } freeaddrinfo(ai0); *socklist_p = socklist; return socknum; }