94b58e5e11fb7f9c16a5db14374b8079f34c4383
[strongswan.git] / Source / charon / packet.c
1 /**
2 * @file packet.h
3 *
4 * @brief UDP-Packet, contains data, sender and receiver
5 *
6 */
7
8 /*
9 * Copyright (C) 2005 Jan Hutter, Martin Willi
10 * Hochschule fuer Technik Rapperswil
11 *
12 * This program is free software; you can redistribute it and/or modify it
13 * under the terms of the GNU General Public License as published by the
14 * Free Software Foundation; either version 2 of the License, or (at your
15 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * for more details.
21 */
22
23 #include "allocator.h"
24 #include "packet.h"
25
26
27 static status_t destroy(packet_t *this)
28 {
29 if (this->data.ptr != NULL)
30 {
31 allocator_free(this->data.ptr);
32 }
33 allocator_free(this);
34 return SUCCESS;
35 }
36
37 /**
38 * @brief helper function to set address used by set_dest & set_source
39 */
40 static status_t set_addr(int family, struct sockaddr *saddr, char *address, u_int16_t port)
41 {
42 switch (family)
43 {
44 /* IPv4 */
45 case AF_INET:
46 {
47 struct sockaddr_in *sin = (struct sockaddr_in*)saddr;
48 sin->sin_family = AF_INET;
49 sin->sin_addr.s_addr = inet_addr("127.0.0.1");
50 sin->sin_port = htons(port);
51 return SUCCESS;;
52 }
53 }
54 return NOT_SUPPORTED;
55 }
56
57 status_t set_destination(packet_t *this, char *address, u_int16_t port)
58 {
59 struct sockaddr *saddr = &(this->destination);
60 return set_addr(this->family, saddr, address, port);
61 }
62
63 status_t set_source(packet_t *this, char *address, u_int16_t port)
64 {
65 struct sockaddr *saddr = &(this->source);
66 return set_addr(this->family, saddr, address, port);
67 }
68
69
70 packet_t *packet_create(int family)
71 {
72 packet_t *this = allocator_alloc_thing(packet_t);
73
74 this->destroy = destroy;
75 this->set_destination = set_destination;
76 this->set_source = set_source;
77
78 this->family = family;
79 switch (family)
80 {
81 case AF_INET:
82 this->sockaddr_len = sizeof(struct sockaddr_in);
83 break;
84 default: /* not supported */
85 allocator_free(this);
86 return NULL;
87 }
88
89 this->data.len = 0;
90 this->data.ptr = NULL;
91 return this;
92 }