giuliomoro@44: /* giuliomoro@44: * udpClient.cpp giuliomoro@44: * giuliomoro@44: * Created on: 19 May 2015 giuliomoro@44: * Author: giulio moro giuliomoro@44: */ giuliomoro@44: #include "../include/UdpClient.h" giuliomoro@44: giuliomoro@44: UdpClient::UdpClient(){ giuliomoro@53: outSocket=socket(AF_INET, SOCK_DGRAM, 0); giuliomoro@53: isSetPort=false; giuliomoro@53: isSetServer=false; giuliomoro@44: enabled=false; giuliomoro@44: } giuliomoro@44: UdpClient::UdpClient(int aPort, const char* aServerName){ giuliomoro@44: outSocket=socket(AF_INET, SOCK_DGRAM, 0); giuliomoro@44: if(outSocket<0){ giuliomoro@44: enabled=false; giuliomoro@44: return; giuliomoro@44: } giuliomoro@44: setPort(aPort); giuliomoro@44: setServer(aServerName); giuliomoro@53: isSetPort=true; giuliomoro@53: isSetServer=true; giuliomoro@44: enabled=true; giuliomoro@44: } giuliomoro@44: UdpClient::~UdpClient(){ giuliomoro@44: close(outSocket); giuliomoro@44: } giuliomoro@44: void UdpClient::setPort(int aPort){ giuliomoro@44: port=aPort; giuliomoro@44: destinationServer.sin_port = htons(port); giuliomoro@44: destinationServer.sin_family = AF_INET; giuliomoro@53: isSetPort=true; giuliomoro@53: if(isSetServer){ giuliomoro@53: enabled=true; giuliomoro@53: } giuliomoro@44: }; giuliomoro@44: void UdpClient::setServer(const char* aServerName){ giuliomoro@44: inet_pton(AF_INET,aServerName,&destinationServer.sin_addr); giuliomoro@53: isSetServer=true; giuliomoro@53: if(isSetPort){ giuliomoro@53: enabled=true; giuliomoro@53: } giuliomoro@44: }; giuliomoro@44: int UdpClient::send(void * message, int size){ giuliomoro@44: if(!enabled) giuliomoro@44: return -1; giuliomoro@44: unsigned int length; giuliomoro@44: length=sizeof(struct sockaddr_in); giuliomoro@44: int n=sendto(outSocket,message,size,0,(const struct sockaddr *)&destinationServer,length); giuliomoro@53: if (n < 0){ giuliomoro@44: return n; giuliomoro@53: } giuliomoro@44: return 1; giuliomoro@44: }; giuliomoro@44: