evutil_socket_t ccnet_net_bind_v4 (const char *ipaddr, int *port) { evutil_socket_t sockfd; struct sockaddr_in addr; int on = 1; sockfd = socket (AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { ccnet_warning("create socket failed: %s\n", strerror(errno)); exit(-1); } memset (&addr, 0, sizeof (struct sockaddr_in)); addr.sin_family = AF_INET; if (inet_aton(ipaddr, &addr.sin_addr) == 0) { ccnet_warning ("Bad ip address %s\n", ipaddr); return -1; } addr.sin_port = htons (*port); if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0) { ccnet_warning ("setsockopt of SO_REUSEADDR error: %s\n", strerror(errno)); return -1; } if ( bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { ccnet_warning ("Bind error: %s\n", strerror (errno)); return -1; } if (*port == 0) { struct sockaddr_storage ss; socklen_t len; len = sizeof(ss); if (getsockname(sockfd, (struct sockaddr *)&ss, &len) < 0) { ccnet_warning ("getsockname error: %s\n", strerror(errno)); return -1; } *port = sock_port ((struct sockaddr *)&ss); } return sockfd; }
static int64_t HHVM_METHOD(UVUdp, getSockport) { auto* data = Native::data<UVUdpData>(this_); struct sockaddr addr; int addrlen; if(data->udp_handle->sockPort == 0){ addrlen = sizeof addr; if(uv_udp_getsockname(data->udp_handle, &addr, &addrlen)){ return -1; } data->udp_handle->sockAddr = sock_addr(&addr); data->udp_handle->sockPort = sock_port(&addr); } return data->udp_handle->sockPort; }
static void send_cb(uv_udp_send_t* sr, int status) { send_req_t *req = (send_req_t *) sr; uv_udp_ext_t *udp_handle = (uv_udp_ext_t *) req->handle; auto* data = Native::data<UVUdpData>(udp_handle->udp_object_data); auto callback = data->sendCallback; if(!callback.isNull()){ vm_call_user_func(callback, make_packed_array( udp_handle->udp_object_data, sock_addr((struct sockaddr *) &req->addr), sock_port((struct sockaddr *) &req->addr), status ) ); } delete req->buf.base; delete req; }
static void recv_cb(uv_udp_ext_t* udp_handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags) { auto* data = Native::data<UVUdpData>(udp_handle->udp_object_data); auto recvCallback = data->recvCallback; auto errorCallback = data->errorCallback; if(nread > 0){ if(!recvCallback.isNull()){ vm_call_user_func(recvCallback, make_packed_array( udp_handle->udp_object_data, sock_addr((struct sockaddr *) addr), sock_port((struct sockaddr *) addr), String(buf->base, nread, CopyString), (int64_t) flags ) ); } } else{ if(!errorCallback.isNull()){ vm_call_user_func(errorCallback, make_packed_array(udp_handle->udp_object_data, nread, (int64_t) flags)); } } delete buf->base; }