コード例 #1
0
ファイル: WSASendTo.cpp プロジェクト: IFGHou/Holodeck
BOOL My_WSASendTo()
{
	SOCKET s=NULL;
	LPWSABUF lpBuffers=NULL;
	DWORD dwBufferCount=NULL;
	LPDWORD lpNumberOfBytesSent=NULL;
	DWORD dwFlags=NULL;
	const struct sockaddr FAR * lpTo=NULL;
	int iTolen=NULL;
	LPWSAOVERLAPPED lpOverlapped=NULL;
	LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine=NULL;
	int returnVal_Real = NULL;
	int returnVal_Intercepted = NULL;

	DWORD error_Real = 0;
	DWORD error_Intercepted = 0;
	__try{
	disableInterception();
	returnVal_Real = WSASendTo (s,lpBuffers,dwBufferCount,lpNumberOfBytesSent,dwFlags,lpTo,iTolen,lpOverlapped,lpCompletionRoutine);
	error_Real = GetLastError();
	enableInterception();
	returnVal_Intercepted = WSASendTo (s,lpBuffers,dwBufferCount,lpNumberOfBytesSent,dwFlags,lpTo,iTolen,lpOverlapped,lpCompletionRoutine);
	error_Intercepted = GetLastError();
	}__except(puts("in filter"), 1){puts("exception caught");}
	return ((returnVal_Real == returnVal_Intercepted) && (error_Real == error_Intercepted));
}
コード例 #2
0
ファイル: ClientMode.cpp プロジェクト: razc411/ridingthecode
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: udp_deliver_packets
--
--      DATE: Febuary 6 2014
--      REVISIONS: Countless. Most recent, turning it into somewhat reliable UDP.
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: void udp_deliver_packets(HWND hwnd, int totalBytesRead, int packet_size, int buffer_count, WSABUF * buffers)
--
--      RETURNS: void
--
--      NOTES:
--      Takes the parent window HWND, the total bytes to be transferred (totalBytesRead), the current packet size, the amount of packets
--		an an array of WSABUFs each containing a packet of data.
--		
--		Delivers the packets over UDP to the specified IP and port, and has some reliability for dropped packets by 
--		incorporating an acknowledgement system as well as a header packet containing the info passed to the function. 
--		If an error occurs in the recvfrom portion of the acknowledgement, consider the transfer dead and restart the program.
--
--		* WILL loop endlessly if the user decides to terminate the server during a transfer. Will continously wait for ACKs.
----------------------------------------------------------------------------------------------------------------------*/
void udp_deliver_packets(HWND hwnd, int totalBytesRead, int packet_size, int buffer_count, WSABUF * buffers){

	SETTINGS * st = (SETTINGS*)GetClassLongPtr(hwnd, 0);
	
	int packets_lost = 0;
	int status;
	char msg[MAX_SIZE];
	DWORD  numBytesSent = 0;
	struct sockaddr_in sin;

	char flags[HEADER_SIZE];
	memset(flags, '\0', HEADER_SIZE);
	sprintf_s(flags, ";%d,%d,%d,%d;", totalBytesRead, packet_size, buffer_count, st->mode);

	LPWSABUF wsaHeaderBuf = (LPWSABUF)malloc(sizeof(WSABUF));
	wsaHeaderBuf->len = HEADER_SIZE;
	wsaHeaderBuf->buf = flags;

	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(atoi(st->client_port));

	if ((sin.sin_addr.s_addr = inet_addr(st->client_send_ip)) == INADDR_NONE)
	{
		activity("Failed to find address\n", EB_STATUSBOX);
		return;
	}
	
	while (1){ // transferring the header packet
		if ((status = WSASendTo(st->client_socket, wsaHeaderBuf, 1, &numBytesSent, 0, (struct sockaddr *)&sin, sizeof(sin), NULL, NULL)) < 0){
			sprintf_s(msg, "Error %d in TCP WSASend(header) with return of %d\n", WSAGetLastError(), status);
			activity(msg, EB_STATUSBOX);
		}

		if (receive_acknowledge(hwnd) == 1) { break; } 
		packets_lost++;
	}
	
	startTime = GetTickCount();

	for (int p = 0; p < buffer_count; p++){
		while (1){ // transferring the actual data
			if ((status = WSASendTo(st->client_socket, &buffers[p], 1, &numBytesSent, 0, (struct sockaddr *)&sin, sizeof(sin), NULL, NULL)) < 0){
				sprintf_s(msg, "Error %d in sendto(buffer) with return of %d\n", WSAGetLastError(), status);
				activity(msg, EB_STATUSBOX);
				return;
			}

			if (receive_acknowledge(hwnd) == 1){ break; }
			packets_lost++;
		}
	}

	endTime = GetTickCount();
	seconds = endTime - startTime;
	sprintf_s(msg, "Data transmission completed in %d milliseconds.\n", seconds);
	activity(msg, EB_STATUSBOX);
}
コード例 #3
0
/*
* Sends dgarm to the specified destionation.
*/
tsk_size_t tnet_transport_sendto(const tnet_transport_handle_t *handle, tnet_fd_t from, const struct sockaddr *to, const void* buf, tsk_size_t size)
{
	tnet_transport_t *transport = (tnet_transport_t*)handle;
	WSABUF wsaBuffer;
	DWORD numberOfBytesSent = 0;
	int ret = -1;

	if (!transport){
		TSK_DEBUG_ERROR("Invalid server handle.");
		return ret;
	}

	if (!TNET_SOCKET_TYPE_IS_DGRAM(transport->master->type)){
		TSK_DEBUG_ERROR("In order to use WSASendTo you must use an udp transport.");
		return ret;
	}

	wsaBuffer.buf = (CHAR*)buf;
	wsaBuffer.len = (ULONG)size;

	if ((ret = WSASendTo(from, &wsaBuffer, 1, &numberOfBytesSent, 0, to, tnet_get_sockaddr_size(to), 0, 0)) == SOCKET_ERROR){
		if ((ret = WSAGetLastError()) == WSA_IO_PENDING){
			TSK_DEBUG_INFO("WSA_IO_PENDING error for WSASendTo SSESSION");
			ret = 0;
		}
		else{
			TNET_PRINT_LAST_ERROR("WSASendTo have failed.");
			return ret;
		}
	}
	else ret = 0;

	return numberOfBytesSent;
}
コード例 #4
0
int			GSocketUdpServer::Send(const GString &s)
{
#if defined (GWIN)
	int		rc, err;
	WSABUF	DataBuf;
	DWORD	SendBytes = 0;
	DataBuf.len = s.Size();
	DataBuf.buf = s.ToChar();
	rc = WSASendTo(this->_socket, &DataBuf, 1, &SendBytes, NULL, reinterpret_cast <sockaddr*> (&this->_sockaddr), DataBuf.len, NULL, NULL);
	delete[] DataBuf.buf;
	if ((rc == SOCKET_ERROR) && (WSA_IO_PENDING != (err = WSAGetLastError())))
	{
		this->_lastError = GSocketUdpServer::ERROR_SEND;
		throw GException("GSocketUdpServer", "Error WSASend() !");
	}
	return (SendBytes);
#else
	int	l = 0;
	char	*tmp = s.ToChar();
	l = sendto(this->_socket, tmp, s.Size(), 0, 0, 0);
	delete[] tmp;
	if (l < 0)
	{
		this->_lastError = GSocketUdpServer::ERROR_SEND;
		throw GException("GSocketUdpServer", "Error send() !");
	}
	return (l);
#endif
}
コード例 #5
0
int			GSocketUdpServer::Send(void *s, unsigned int size)
{
#if defined (GWIN)
	int		rc, err;
	WSABUF	DataBuf;
	DWORD	SendBytes = 0;
	DataBuf.len = size;
	DataBuf.buf = (char *)s;
	rc = WSASendTo(this->_socket, &DataBuf, 1, &SendBytes, NULL, reinterpret_cast <sockaddr*> (&this->_sockaddr), DataBuf.len, NULL, NULL);
	if ((rc == SOCKET_ERROR) && (WSA_IO_PENDING != (err = WSAGetLastError())))
	{
		this->_lastError = GSocketUdpServer::ERROR_SEND;
		throw GException("GSocketUdpServer", "Error WSASend() !");
	}
	return (SendBytes);
#else
	int	l = 0;
	l = sendto(this->_socket, s, size, 0, 0, 0);
	if (l < 0)
	{
		this->_lastError = GSocketUdpServer::ERROR_SEND;
		throw GException("GSocketUdpServer", "Error send() !");
	}
	return (l);
#endif
}
コード例 #6
0
ファイル: win32.c プロジェクト: cgutman/enet
int
enet_socket_send (ENetSocket socket,
                  const ENetAddress * address,
                  const ENetBuffer * buffers,
                  size_t bufferCount)
{
    DWORD sentLength;

    if (WSASendTo (socket, 
                   (LPWSABUF) buffers,
                   (DWORD) bufferCount,
                   & sentLength,
                   0,
                   address != NULL ? (struct sockaddr *) & address -> address : NULL,
                   address != NULL ? address -> addressLength : 0,
                   NULL,
                   NULL) == SOCKET_ERROR)
    {
       if (WSAGetLastError () == WSAEWOULDBLOCK)
         return 0;

       return -1;
    }

    return (int) sentLength;
}
コード例 #7
0
ファイル: win32.c プロジェクト: thewolfwillcome/enet
int
enet_socket_send (ENetSocket socket,
                  const ENetAddress * address,
                  const ENetBuffer * buffers,
                  size_t bufferCount)
{
    ENetAddress address_clone;
    int address_length = enet_address_get_size (address);
    DWORD sentLength;

    if (address != NULL)
    {
        memcpy (& address_clone, address, address_length);

        address_clone.port = ENET_HOST_TO_NET_16 (address -> port);
    }

    if (WSASendTo (socket,
                   (LPWSABUF) buffers,
                   (DWORD) bufferCount,
                   & sentLength,
                   0,
                   address != NULL ? (struct sockaddr *) & address_clone : NULL,
                   address != NULL ? address_length : 0,
                   NULL,
                   NULL) == SOCKET_ERROR)
    {
       if (WSAGetLastError () == WSAEWOULDBLOCK)
         return 0;

       return -1;
    }

    return (int) sentLength;
}
コード例 #8
0
ファイル: winio.c プロジェクト: primitivorm/kaffe
static
ssize_t
Nsendto(int fd, const void* buf, size_t len, int flags, const struct sockaddr* addr, int alen)
{
    ssize_t r;
    int res;
    WSABUF wbuf;

    wbuf.len = (u_long)len;
    wbuf.buf = (char FAR*)buf;

    if (addr != NULL)
        res = WSASendTo(fhand[fd].sock, &wbuf, 1, &r, flags,
                        addr, alen, NULL, NULL);
    else
        res = WSASend(fhand[fd].sock, &wbuf, 1, &r, flags, NULL, NULL);

    if (res == SOCKET_ERROR) {
        int err = WSAGetLastError();
        return (-1);
    }
    else {
        return (r);
    }
}
コード例 #9
0
ファイル: udp_peer.c プロジェクト: github188/tinylib
/* 由于udp的简单性,请使用者自行完成报文分片,保证每次的message尺寸小于mtu, 本发送接口只做简单发送,不做缓存重发 */
int udp_peer_send(udp_peer_t* peer, const void *message, unsigned len, const inetaddr_t *peer_addr)
{
    struct sockaddr_in addr;
    WSABUF wsabuf;
    DWORD written;
    int ret;

    if (NULL == peer || NULL == message || 0 == len || 65535 < len || NULL == peer_addr)
    {
        log_error("udp_peer_send: bad peer(%p) or bad message(%p) or bad len(%u) or bad peer_addr(%p)", 
            peer, message, len, peer_addr);
        return -1;
    }

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(peer_addr->ip);
    addr.sin_port = htons(peer_addr->port);

    memset(&wsabuf, 0, sizeof(wsabuf));
    wsabuf.len = len;
    wsabuf.buf = (char*)message;

    ret = 0;
    written = 0;
    WSASendTo(peer->fd, &wsabuf, 1, &written, 0, (struct sockaddr*)&addr, sizeof(addr), NULL, NULL);
    if (written != len)
    {
        log_warn("udp_peer_send: WSASendTo() failed, errno: %d", WSAGetLastError());
        ret = -1;
    }

    return ret;
}
コード例 #10
0
void CWin32Socket::SendTo(TWin32Message& aMessage)
	{
	__ASSERT_DEBUG((iSendMessage == NULL) && (iBytesSent == 0), Panic(EWinSockPrtCWin32SocketMultipleSendToRequests));
	iSendMessage = &aMessage;
	WSP_LOG(WspLog::Printf(_L("CWin32Socket::SendTo: this: 0x%x, bytes to send: %d"), this, iSendMessage->ReadBuffer().Length()));
	TPtrC8 bufPtr(iSendMessage->ReadBuffer());
	iSendBuffer.buf = reinterpret_cast<char*>(const_cast<TUint8*>(bufPtr.Ptr()));
	iSendBuffer.len = bufPtr.Length();
	iSendOverlapped.hEvent = (void*) this;
	TInetAddr address;
	address.Copy(iSendMessage->WriteBuffer());
	SOCKADDR_IN winSockAddress;
	ConvertAddress(address, winSockAddress);
	DWORD numberOfBytesSent;
	TInt ret = WSASendTo(iSocket, &iSendBuffer, 1, &numberOfBytesSent, 0, (LPSOCKADDR)&winSockAddress, sizeof(struct sockaddr_in), &iSendOverlapped, &SendToCompletion);
	if (ret == SOCKET_ERROR)
		{
		TInt err = WSAGetLastError();
		if (err != WSA_IO_PENDING)
			{
			WSP_LOG(WspLog::Printf(_L("\tsocket error: %d"), err));
			Complete(iSendMessage, MapWinSockError(err));
			}
		}
	}
コード例 #11
0
ファイル: udp_peer.c プロジェクト: github188/tinylib
int udp_peer_send2(udp_peer_t* peer, const void *message, unsigned len, const struct sockaddr_in *peer_addr)
{
    WSABUF wsabuf;
    DWORD written;
    int ret;

    if (NULL == peer || NULL == message || 0 == len || 65535 < len || NULL == peer_addr)
    {
        log_error("udp_peer_send2: bad peer(%p) or bad message(%p) or bad len(%u) or bad peer_addr(%p)", 
            peer, message, len, peer_addr);
        return -1;
    }

    memset(&wsabuf, 0, sizeof(wsabuf));
    wsabuf.len = len;
    wsabuf.buf = (char*)message;

    ret = 0;
    written = 0;
    WSASendTo(peer->fd, &wsabuf, 1, &written, 0, (struct sockaddr*)peer_addr, sizeof(*peer_addr), NULL, NULL);
    if (written != len)
    {
        log_warn("udp_peer_send2: WSASendTo() failed, errno: %d", WSAGetLastError());
        ret = -1;
    }

    return ret;
}
コード例 #12
0
ファイル: win32.c プロジェクト: Badcreature/caffeine-hx
int
enet_socket_send (ENetSocket socket,
                  const ENetAddress * address,
                  const ENetBuffer * buffers,
                  size_t bufferCount)
{
    struct sockaddr_in sin;
    DWORD sentLength;

    if (address != NULL)
    {
        sin.sin_family = AF_INET;
        sin.sin_port = ENET_HOST_TO_NET_16 (address -> port);
        sin.sin_addr.s_addr = address -> host;
    }

    if (WSASendTo (socket, 
                   (LPWSABUF) buffers,
                   (DWORD) bufferCount,
                   & sentLength,
                   0,
                   address != NULL ? (struct sockaddr *) & sin : 0,
                   address != NULL ? sizeof (struct sockaddr_in) : 0,
                   NULL,
                   NULL) == SOCKET_ERROR)
    {
       if (WSAGetLastError () == WSAEWOULDBLOCK)
         return 0;

       return -1;
    }

    return (int) sentLength;
}
コード例 #13
0
ファイル: io.c プロジェクト: beebee/peervpn
// Sends an IPv4 UDP packet. Returns length of sent message.
static int ioSendUDPv4Packet(struct s_io_state *iostate, const unsigned char *buf, const int len, const struct s_io_v4addr *destination) {
	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(struct sockaddr_in));
	addr.sin_family = AF_INET;
	memcpy(&addr.sin_addr.s_addr, destination->addr, 4);
	memcpy(&addr.sin_port, destination->port, 2);
#ifdef IO_WINDOWS
	DWORD ret = 0;
	DWORD flags = 0;
	WSABUF wsabuf;
	wsabuf.buf = (char *)buf;
	wsabuf.len = len;
	WSASendTo(iostate->fd[IO_FDID_UDPV4SOCKET].fd, &wsabuf, 1, NULL, flags, (struct sockaddr *)&addr, sizeof(struct sockaddr_in), &iostate->overlapped_write[IO_FDID_UDPV4SOCKET], NULL);
	WSAGetOverlappedResult(iostate->fd[IO_FDID_UDPV4SOCKET].fd, &iostate->overlapped_write[IO_FDID_UDPV4SOCKET], &ret, TRUE, &flags);
#else
	int ret;
	ret = sendto(iostate->fd[IO_FDID_UDPV4SOCKET].fd, buf, len, 0, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
#endif
	if(ret > 0) {
		return ret;
	}
	else {
		return 0;
	}
}
コード例 #14
0
ファイル: UDPWinSocket.cpp プロジェクト: smootise/R-Type
bool	UDPWinSocket::Send_data(ClientMessage *send_msg)
{
	DWORD				send_flags = 0;
	DWORD				sent_bytes = 0;
	WSABUF				sendbuff[1];
	char				buff[8192];
	int					server_length;

	sendbuff[0].len = 8192;
	sendbuff[0].buf = buff;
	server_length = (int)sizeof(struct sockaddr_in);

	//on memset le buff
	memset(buff, '\0', 8192);
	//on copie les bails
	memcpy(&buff, (void *)send_msg, sizeof(ClientMessage));
	if ((WSASendTo(_socket, sendbuff, 1, &sent_bytes, send_flags, (struct sockaddr *)&_server, server_length, NULL, NULL)) == SOCKET_ERROR)
	{
		if (WSAGetLastError() == WSAEWOULDBLOCK)
			return (true);
		else
		{
			std::cerr << "coudldn't use send to" << std::endl;
			return (true);
		}
	}
	return (true);
}
コード例 #15
0
ファイル: WinSocketUdp.cpp プロジェクト: fiahil/R-Type
void SocketUdp::Send(const std::string& packet)
{
	SOCKADDR_IN sin;

	DEBUG << "Sending in progress" << std::endl;
	for (std::list<EndPoint*>::iterator it = this->client_.begin() ; it != this->client_.end() ; ++it) { 
		sin.sin_family = AF_INET;
		sin.sin_addr.s_addr = inet_addr((*it)->getIpStr().c_str());
		WSAHtons(this->socket_, (*it)->getPort(), &sin.sin_port);

		WSABUF* fb = new WSABUF();
		CHAR* buffer = new CHAR[sizeof(UDPPacket)];
		PackManUDP::Memcpy(buffer, packet.data(), packet.size());
		fb->buf = buffer;
		fb->len = sizeof(UDPPacket);

		DWORD sended = 0;

		if (WSASendTo(this->socket_, fb, 1, &sended, 0, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin), 0, 0) == SOCKET_ERROR)
			throw ErrorInOut("Cannot send data");
		DEBUG << "Sending completed" << std::endl;

		delete fb;
		delete buffer;
	}
}
コード例 #16
0
ファイル: net_win32.c プロジェクト: ARMinARM/elua
net_ssize_t net_sendto( NET_SOCKET s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen )
{
  DWORD wrotebytes;
  WSABUF datadesc = { len, ( char* )buf };
    
  if( WSASendTo( s->s, &datadesc, 1, &wrotebytes, flags, to, tolen, NULL, NULL ) == SOCKET_ERROR )
    return 0;
  return wrotebytes;
}
コード例 #17
0
unsigned int DexUDPSendPacket( DexUDP *dex_udp_parameters, const char data[DEX_UDP_PACKET_SIZE] )
{
	
	DWORD	  dwBytesSent = 0;
	DWORD     dwFlags = 0;
	WSABUF    wbSend;
	
	int       status;
	
	static    count = 0;
	
	wbSend.buf = (char *) data;	
	wbSend.len = DEX_UDP_PACKET_SIZE;
	
	// Send packet to the local host no matter what.
	status = WSASendTo( dex_udp_parameters->socket, 
		&wbSend, 1, 
		&dwBytesSent, 
		dwFlags, 
		(SOCKADDR*) &localXmitAddr, 
		LocalAddrSize,
		NULL, NULL);
	
	// Broadcast to the net only if a valid broadcast address was already set.
	if ( dex_udp_parameters->sockaddr.sin_addr.s_addr ) {
		status = WSASendTo( dex_udp_parameters->socket, 
			&wbSend, 1, 
			&dwBytesSent, 
			dwFlags, 
			(SOCKADDR*) &dex_udp_parameters->sockaddr, 
			sizeof( dex_udp_parameters->sockaddr ),
			NULL, NULL);
	}
	
	if ( status ) {
		status = WSAGetLastError();
		dwBytesSent = 0;
	}
	
	return( dwBytesSent );
	
}
コード例 #18
0
ファイル: channel.cpp プロジェクト: eHomeTechnology/HDEvideo
int CChannel::sendto(const sockaddr* addr, CPacket& packet) const
{
    // convert control information into network order
    if (packet.getFlag())
        for (int i = 0, n = packet.getLength() / 4; i < n; ++ i)
            *((uint32_t *)packet.m_pcData + i) = htonl(*((uint32_t *)packet.m_pcData + i));

    // convert packet header into network order
    //for (int j = 0; j < 4; ++ j)
    //   packet.m_nHeader[j] = htonl(packet.m_nHeader[j]);
    uint32_t* p = packet.m_nHeader;
    for (int j = 0; j < 4; ++ j)
    {
        *p = htonl(*p);
        ++ p;
    }

#ifndef WIN32
    msghdr mh;
    mh.msg_name = (sockaddr*)addr;
    mh.msg_namelen = m_iSockAddrSize;
    mh.msg_iov = (iovec*)packet.m_PacketVector;
    mh.msg_iovlen = 2;
    mh.msg_control = NULL;
    mh.msg_controllen = 0;
    mh.msg_flags = 0;

    int res = (int)sendmsg(m_iSocket, &mh, 0);
#else
    DWORD size = CPacket::m_iPktHdrSize + packet.getLength();
    int addrsize = m_iSockAddrSize;
    int res = WSASendTo(m_iSocket, (LPWSABUF)packet.m_PacketVector, 2, &size, 0, addr, addrsize, NULL, NULL);
    res = (0 == res) ? size : -1;
#endif

    // convert back into local host order
    //for (int k = 0; k < 4; ++ k)
    //   packet.m_nHeader[k] = ntohl(packet.m_nHeader[k]);
    p = packet.m_nHeader;
    for (int k = 0; k < 4; ++ k)
    {
        *p = ntohl(*p);
        ++ p;
    }

    if (packet.getFlag())
    {
        for (int l = 0, n = packet.getLength() / 4; l < n; ++ l)
            *((uint32_t *)packet.m_pcData + l) = ntohl(*((uint32_t *)packet.m_pcData + l));
    }

    return res;
}
コード例 #19
0
bool Socket::EndSend(OverlappedTransferBuffer *sendBuffer)
{
	assert(sendBuffer);
	if (!sendBuffer)
		return false;

	// For the purposes of this send, mark the allocated length of the send buffer equal to the 
	// number of bytes the user had filled into the buffer.
	sendBuffer->buffer.len = sendBuffer->bytesContains;

#ifdef WIN32
	// Clear the event flag so that the completion of WSASend can trigger this and signal us.
	WSAResetEvent(sendBuffer->overlapped.hEvent);

	unsigned long bytesSent = 0;

	int ret;

	if (transport == SocketOverUDP)
		ret = WSASendTo(connectSocket, &sendBuffer->buffer, 1, (LPDWORD)&bytesSent, 0, (sockaddr*)&udpPeerAddress, sizeof(udpPeerAddress), &sendBuffer->overlapped, 0);
	else
		ret = WSASend(connectSocket, &sendBuffer->buffer, 1, (LPDWORD)&bytesSent, 0, &sendBuffer->overlapped, 0);

	int error = (ret == 0) ? 0 : Network::GetLastError();
	if (ret != 0 && error != WSA_IO_PENDING)
	{
		if (error != KNET_EWOULDBLOCK)
		{
			LOG(LogError, "Socket::EndSend() failed! Error: %s.", Network::GetErrorString(error).c_str());
			if (!IsUDPServerSocket())
				writeOpen = false;
		}
		DeleteOverlappedTransferBuffer(sendBuffer);
		return false;
	}

	bool success = queuedSendBuffers.Insert(sendBuffer);
	if (!success)
	{
		LOG(LogError, "queuedSendBuffers.Insert(send); failed!");
		///\todo WARNING: Deleting a buffer that is submitted to WSASend. This crashes. The alternative
		/// is to leak. Refactor so that the above queuedSendBuffers.Insert is tried for success before calling WSASend.
		DeleteOverlappedTransferBuffer(sendBuffer);
		return false;
	}
	return true;

#elif defined(UNIX) || defined(ANDROID)
	bool success = Send(sendBuffer->buffer.buf, sendBuffer->buffer.len);
	DeleteOverlappedTransferBuffer(sendBuffer);
	return success;
#endif
}
コード例 #20
0
ssize_t
ngx_udp_wsasend(ngx_connection_t *c, u_char *buf, size_t size)
{
    int           n;
    u_long        sent;
    ngx_err_t     err;
    ngx_event_t  *wev;
    WSABUF        wsabuf;	

    wev = c->write;

    if (!wev->ready) {
        return NGX_AGAIN;
    }

    /*
     * WSABUF must be 4-byte aligned otherwise
     * WSASend() will return undocumented WSAEINVAL error.
     */

    wsabuf.buf = (char *) buf;
    wsabuf.len = size;

    sent = 0;    
    
	n = WSASendTo(c->fd,&wsabuf,1,&sent,0,c->sockaddr, c->socklen,NULL,NULL);

    ngx_log_debug4(NGX_LOG_DEBUG_EVENT, c->log, 0,
                   "WSASend: fd:%d, %d, %ul of %uz", c->fd, n, sent, size);

    if (n == 0) {
        if (sent < size) {
            wev->ready = 0;
        }

        c->sent += sent;

        return sent;
    }

    err = ngx_socket_errno;

    if (err == WSAEWOULDBLOCK) {
        ngx_log_debug0(NGX_LOG_DEBUG_EVENT, c->log, err, "WSASend() not ready");
        wev->ready = 0;
        return NGX_AGAIN;
    }

    wev->error = 1;
    ngx_connection_error(c, err, "WSASend() failed");

    return NGX_ERROR;
}
コード例 #21
0
ファイル: UDPSocket.cpp プロジェクト: Forstulen/projects
bool			Network::UDPSocketWindows::sendPacket(Packet const &p, struct sockaddr const *sockAddr) const
{
  DWORD			flags = 0;
  DWORD			bytesSent = 0;
  WSABUF		buf;

  buf.len = p.getSize();
  buf.buf = const_cast<char*>(reinterpret_cast<char const *>(&p.getContent()));

	if (WSASendTo(this->fd_,&buf, 1, &bytesSent, 0, sockAddr, sizeof(*sockAddr), 0, 0) == -1)
    return (false);
  return (true);
}
コード例 #22
0
ファイル: WinSocket.cpp プロジェクト: Nedwor/rtype
	Databuf.buf = (char *)buffer;
	receive = blocksize;
	int size = sizeof(in);
	if ((len = WSARecvFrom(this->sock, &Databuf, 1, &receive, 0, (SOCKADDR *)& in, &size, 0, 0)) ==  SOCKET_ERROR)
		return (-1);
	char cip[32];
	if ((ip = InetNtop( AF_INET, &in, cip, 32)) == "")
		{
			wprintf(L"InetNtop failed with error %u\n", WSAGetLastError());
			return -1;
		}
	return len;
}

int WinSocket::sendBinaryTo(void* data, std::string const &host, int port, int size)
コード例 #23
0
ファイル: Client.cpp プロジェクト: MartinMinkov/COMP4985
/*-------------------------------------------------------------------------------------------------------------------------------------

	FUNCTION:		sendControlUDP

	INTERFACE:		void sendControlUDP(LPSOCKET_INFORMATION SI, struct	sockaddr_in server, char* message, int sizeOfPackets)

	RETURNS:		void

	NOTES:			Sends the control information to a UDP socket

--------------------------------------------------------------------------------------------------------------------------------------*/
void sendControlUDP(LPSOCKET_INFORMATION SI, struct	sockaddr_in server, char* message, int sizeOfPackets)
{
	initSockInfo(SI, message, strlen(message));

	//Send control data
	if (WSASendTo(SI->Socket, &(SI->DataBuf), 1, &SI->BytesSEND, 0, (struct sockaddr *)&server, sizeof(server), &(SI->Overlapped), NULL) == SOCKET_ERROR)
	{
		if (WSAGetLastError() != ERROR_IO_PENDING)
		{
			formatMessage("Sending control information failed");
			ExitThread(1);
		}
	}
	formatMessage("Sending Control Data to Server");
}
コード例 #24
0
ファイル: udp.c プロジェクト: 0-wiz-0/libuv
static int uv__send(uv_udp_send_t* req,
                    uv_udp_t* handle,
                    const uv_buf_t bufs[],
                    unsigned int nbufs,
                    const struct sockaddr* addr,
                    unsigned int addrlen,
                    uv_udp_send_cb cb) {
  uv_loop_t* loop = handle->loop;
  DWORD result, bytes;

  uv_req_init(loop, (uv_req_t*) req);
  req->type = UV_UDP_SEND;
  req->handle = handle;
  req->cb = cb;
  memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped));

  result = WSASendTo(handle->socket,
                     (WSABUF*)bufs,
                     nbufs,
                     &bytes,
                     0,
                     addr,
                     addrlen,
                     &req->u.io.overlapped,
                     NULL);

  if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) {
    /* Request completed immediately. */
    req->u.io.queued_bytes = 0;
    handle->reqs_pending++;
    handle->send_queue_size += req->u.io.queued_bytes;
    handle->send_queue_count++;
    REGISTER_HANDLE_REQ(loop, handle, req);
    uv_insert_pending_req(loop, (uv_req_t*)req);
  } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) {
    /* Request queued by the kernel. */
    req->u.io.queued_bytes = uv__count_bufs(bufs, nbufs);
    handle->reqs_pending++;
    handle->send_queue_size += req->u.io.queued_bytes;
    handle->send_queue_count++;
    REGISTER_HANDLE_REQ(loop, handle, req);
  } else {
    /* Send failed due to an error. */
    return WSAGetLastError();
  }

  return 0;
}
コード例 #25
0
ファイル: io.c プロジェクト: hideman-ltd/peervpn
// Sends an UDP packet. Returns length of sent message.
 int ioHelperSendTo(struct s_io_handle *handle, const unsigned char *send_buf, const int send_buf_size, const struct sockaddr *destination_sockaddr, const socklen_t destination_sockaddr_len) {
	int len;

#if defined(IO_LINUX) || defined(IO_BSD)

	len = sendto(handle->fd, send_buf, send_buf_size, 0, destination_sockaddr, destination_sockaddr_len);

#elif defined(IO_WINDOWS)

	int ovlw_used;
	WSABUF wsabuf;
	DWORD flags;
	DWORD dwlen;

	len = 0;
	wsabuf.buf = (char *)send_buf;
	wsabuf.len = send_buf_size;
	flags = 0;
	ovlw_used = 0;
	if(WSASendTo(handle->fd, &wsabuf, 1, NULL, flags, destination_sockaddr, destination_sockaddr_len, &handle->ovlw, NULL) == 0) {
		ovlw_used = 1;
	}
	else {
		if(WSAGetLastError() == WSA_IO_PENDING) {
			ovlw_used = 1;
		}
	}
	if(ovlw_used) {
		if(WSAGetOverlappedResult(handle->fd, &handle->ovlw, &dwlen, TRUE, &flags) == TRUE) {	
			len = dwlen;
		}
		ResetEvent(handle->ovlw.hEvent);
	}

#else

	#error not implemented
	len = 0;

#endif

	if(len > 0) {
		return len;
	}
	else {
		return 0;
	}
}
コード例 #26
0
int		UDPClientSocketWindows::SNWrite(const char *msg, unsigned int size)
{
	WSABUF	DataBuff;
	DWORD SendBytes;
	DWORD Flags = 0;

	DataBuff.buf = const_cast <char *> (msg);
	DataBuff.len = size;
	if (WSASendTo(this->_socket, &DataBuff, 1, &SendBytes, Flags, (SOCKADDR *)&(this->_servaddr), sizeof(this->_servaddr), NULL, NULL) == SOCKET_ERROR)
		{
			this->_error = CANTWRITE;
			return (-1);
		}
	this->_error = NOERRORSOCKET;
	return (SendBytes);
}
コード例 #27
0
ファイル: udp.c プロジェクト: ajafff/node
int uv__udp_try_send(uv_udp_t* handle,
                     const uv_buf_t bufs[],
                     unsigned int nbufs,
                     const struct sockaddr* addr,
                     unsigned int addrlen) {
  DWORD bytes;
  const struct sockaddr* bind_addr;
  struct sockaddr_storage converted;
  int err;

  assert(nbufs > 0);

  err = uv__convert_to_localhost_if_unspecified(addr, &converted);
  if (err)
    return err;

  /* Already sending a message.*/
  if (handle->send_queue_count != 0)
    return UV_EAGAIN;

  if (!(handle->flags & UV_HANDLE_BOUND)) {
    if (addrlen == sizeof(uv_addr_ip4_any_))
      bind_addr = (const struct sockaddr*) &uv_addr_ip4_any_;
    else if (addrlen == sizeof(uv_addr_ip6_any_))
      bind_addr = (const struct sockaddr*) &uv_addr_ip6_any_;
    else
      return UV_EINVAL;
    err = uv_udp_maybe_bind(handle, bind_addr, addrlen, 0);
    if (err)
      return uv_translate_sys_error(err);
  }

  err = WSASendTo(handle->socket,
                  (WSABUF*)bufs,
                  nbufs,
                  &bytes,
                  0,
                  (const struct sockaddr*) &converted,
                  addrlen,
                  NULL,
                  NULL);

  if (err)
    return uv_translate_sys_error(WSAGetLastError());

  return bytes;
}
コード例 #28
0
ファイル: commiocp.c プロジェクト: yykxx/GGSDDU
/* write operation on common fd (udp)
 * @Handle -- the common fd
 * @Dst -- destination address information
 * @DstLen -- sizeof Dst
 * @Buffer -- data buffer
 * @BufferSize -- size of data to write
 * @Callback -- callback function when write successful
 * @Args -- argument to callback
 * return TRUE -- success, else error
 */
BOOL 
CommIOCPUdpWrite(
    COMMFD_HANDLE Handle, 
    PSOCKADDR Dst,
    INT DstLen,
    PBYTE Buffer, 
    DWORD BufferSize, 
    WRITE_CALLBACK Callback,
    PVOID Args
    )
{
    INT Ret;
    PCOMMIOCP CommIOCP;
    PCOMM_SOCKET_IO_CTX IOData;
    DWORD Flags = 0, Bytes = 0;
    PCOMMFD Commfd = (PCOMMFD)Handle;

    if (!Callback || !Commfd || Commfd->Type != COMM_UDP || Commfd->Handle.Socket == INVALID_SOCKET) {
        LOG_ERROR("bad args");
        return (FALSE);
    }

    CommIOCP = Commfd->CommIOCP;
    
    IOData = (PCOMM_SOCKET_IO_CTX)CommIOCPIOCtxCreate(Commfd->CommIOCP, IO_SOCK_WRITE);
    if (IOData == NULL) {
        LOG_ERROR("create socket IO context failed");
        return (FALSE);
    }

    IOData->WSABuffer.buf = (CHAR *)Buffer;
    IOData->WSABuffer.len = BufferSize;
    IOData->Data.Callback.Write = Callback;
    IOData->Data.Args = Args;

    CommIOCPFDAddRef(Commfd);
    Ret = WSASendTo(Commfd->Handle.Socket, &IOData->WSABuffer, 1, &Bytes, Flags, Dst, DstLen, &IOData->Data.OL, NULL);

    if (Ret == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING) {
        LOG_ERROR("WSASendTo failed [%d]", WSAGetLastError());
        CommIOCPIOCtxDestroy(Commfd->CommIOCP, &IOData->Data);
        CommIOCPFDRelease(Commfd);
        return (FALSE);
    }

    return (TRUE);
}
コード例 #29
0
ファイル: aio-socket-iocp.c プロジェクト: ireader/sdk
int aio_socket_sendto_v(aio_socket_t socket, const struct sockaddr *addr, socklen_t addrlen, socket_bufvec_t* vec, int n, aio_onsend proc, void* param)
{
	struct aio_context *ctx = (struct aio_context*)socket;
	struct aio_context_action *aio;
	
	aio = util_alloc(ctx);
	aio->action = iocp_send;
	aio->send.proc = proc;
	aio->send.param = param;

	assert(0 == (AIO_WRITE & InterlockedOr(&ctx->flags, AIO_WRITE)));
	if(SOCKET_ERROR == WSASendTo(ctx->socket, vec, (DWORD)n, NULL/*&dwBytes*/, 0, addr, addrlen, &aio->overlapped, NULL))
	{
		return aio_socket_result(aio, AIO_WRITE);
	}
	return 0;
}
コード例 #30
0
ファイル: Client.cpp プロジェクト: MartinMinkov/COMP4985
/*-------------------------------------------------------------------------------------------------------------------------------------

	FUNCTION:		sendDataUDP

	INTERFACE:		void sendDataUDP(LPSOCKET_INFORMATION SI, sockaddr_in server, char* message, int sizeOfPackets, int numberOfPackets)

	RETURNS:		void

	NOTES:			Sends the data information to a UDP socket

--------------------------------------------------------------------------------------------------------------------------------------*/
void sendDataUDP(LPSOCKET_INFORMATION SI, sockaddr_in server, char* message, int sizeOfPackets, int numberOfPackets)
{
	initSockInfo(SI, message, sizeOfPackets);
	formatMessage("Sending Data to Server");

	for (int i = 0; i < numberOfPackets; i++)
	{
		if (WSASendTo(SI->Socket, &(SI->DataBuf), 1, &SI->BytesSEND, 0, (struct sockaddr *)&server, sizeof(server), &(SI->Overlapped), NULL) == SOCKET_ERROR)
		{
			if (WSAGetLastError() != ERROR_IO_PENDING)
			{
				formatMessage("Sending UDP data information failed");
				ExitThread(1);
			}
		}
		formatMessage("Sending Data to Server");
	}
}