Home  +  Forums  +  C++ and Sockets  +  C++ and SQL: MySQL, sqlite, ODBC  +  Miscellaneous Projects
Logo
~Sockets~
~New~
~Examples~
~Contact~

C++ Socket library tutorial

UDP socket example

Prev   |   Menu   |   Next

The method OnRawData is called when there is something to be read from the udp socket.

UdpTestSocket.h
#ifndef _UDPTESTSOCKET_H
#define _UDPTESTSOCKET_H

#include <UdpSocket.h>


class UdpTestSocket : public UdpSocket
{
public:
	UdpTestSocket(ISocketHandler&);

	void OnRawData(const char *,size_t,struct sockaddr *,socklen_t);
};


#endif // _UDPTESTSOCKET_H

UdpTestSocket.cpp
#include "UdpTestSocket.h"


UdpTestSocket::UdpTestSocket(ISocketHandler& h)
:UdpSocket(h)
{
}


void UdpTestSocket::OnRawData(const char *p,size_t l,struct sockaddr *sa_from,socklen_t sa_len)
{
	if (sa_len == sizeof(struct sockaddr_in)) // IPv4
	{
		struct sockaddr_in sa;
		memcpy(&sa,sa_from,sa_len);
		ipaddr_t a;
		memcpy(&a,&sa.sin_addr,4);
		std::string ip;
		Utility::l2ip(a,ip);
		printf("Received %d bytes from: %s:%d\n", l,ip.c_str(),sa.sin_port);
		printf("%s\n",static_cast<std::string>(p).substr(0,l).c_str());
	}
#ifdef IPPROTO_IPV6 // not all os's are blessed with IPv6
	else
	if (sa_len == sizeof(struct sockaddr_in6)) // IPv6
	{
		struct sockaddr_in6 sa;
		memcpy(&sa,sa_from,sa_len);
		std::string ip;
		Utility::l2ip(sa.sin6_addr,ip);
		printf("(IPv6) Received %d bytes from: %s:%d\n", l,ip.c_str(),sa.sin6_port);
		printf("%s\n",static_cast<std::string>(p).substr(0,l).c_str());
	}
#endif
}

Prev   |   Menu   |   Next

Valid HTML 4.01!

Validate
Page, code, and content Copyright (C) 2021 by Anders Hedström