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