UDPSerializer.cc

Go to the documentation of this file.
00001 //
00002 // Copyright (C) 2005 Christian Dankbar, Irene Ruengeler, Michael Tuexen, Andras Varga
00003 //
00004 // This program is free software; you can redistribute it and/or
00005 // modify it under the terms of the GNU General Public License
00006 // as published by the Free Software Foundation; either version 2
00007 // of the License, or (at your option) any later version.
00008 //
00009 // This program is distributed in the hope that it will be useful,
00010 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012 // GNU General Public License for more details.
00013 //
00014 // You should have received a copy of the GNU General Public License
00015 // along with this program; if not, see <http://www.gnu.org/licenses/>.
00016 //
00017 
00018 #include <platdep/sockets.h>
00019 #include "headers/defs.h"
00020 namespace INETFw // load headers into a namespace, to avoid conflicts with platform definitions of the same stuff
00021 {
00022 #include "headers/bsdint.h"
00023 #include "headers/in.h"
00024 #include "headers/in_systm.h"
00025 #include "headers/udp.h"
00026 };
00027 
00028 #include "UDPSerializer.h"
00029 
00030 #include "TCPIPchecksum.h"
00031 
00032 #if !defined(_WIN32) && !defined(__WIN32__) && !defined(WIN32) && !defined(__CYGWIN__) && !defined(_WIN64)
00033 #include <netinet/in.h>  // htonl, ntohl, ...
00034 #endif
00035 
00036 
00037 using namespace INETFw;
00038 
00039 
00040 int UDPSerializer::serialize(const UDPPacket *pkt, unsigned char *buf, unsigned int bufsize)
00041 {
00042     struct udphdr *udphdr = (struct udphdr *) (buf);
00043     int packetLength;
00044 
00045     packetLength = pkt->getByteLength();
00046     udphdr->uh_sport = htons(pkt->getSourcePort());
00047     udphdr->uh_dport = htons(pkt->getDestinationPort());
00048     udphdr->uh_ulen  = htons(packetLength);
00049     udphdr->uh_sum   = TCPIPchecksum::checksum(buf, packetLength);
00050     return packetLength;
00051 }
00052 
00053 void UDPSerializer::parse(const unsigned char *buf, unsigned int bufsize, UDPPacket *dest)
00054 {
00055 
00056     struct udphdr *udphdr = (struct udphdr*) buf;
00057 
00058     dest->setSourcePort(ntohs(udphdr->uh_sport));
00059     dest->setDestinationPort(ntohs(udphdr->uh_dport));
00060     dest->setByteLength(8);
00061     cPacket *encapPacket = new cPacket("Payload-from-wire");
00062     encapPacket->setByteLength(ntohs(udphdr->uh_ulen) - sizeof(struct udphdr));
00063     dest->encapsulate(encapPacket);
00064     dest->setName(encapPacket->getName());
00065 }