blob: 91cf2fd4b1025ccfdb653e2a32f7291a9ca6c060 [file] [log] [blame]
Mike J. Chen951bd8d2011-08-15 11:59:47 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <arpa/inet.h>
18#include <linux/socket.h>
19
20#include <binder/Parcel.h>
21
22namespace android {
23
24bool canSerializeSockaddr(const struct sockaddr_storage* addr) {
25 switch (addr->ss_family) {
26 case AF_INET:
27 case AF_INET6:
28 return true;
29 default:
30 return false;
31 }
32}
33
34void serializeSockaddr(Parcel* p, const struct sockaddr_storage* addr) {
35 switch (addr->ss_family) {
36 case AF_INET: {
37 const struct sockaddr_in* s =
38 reinterpret_cast<const struct sockaddr_in*>(addr);
39 p->writeInt32(AF_INET);
40 p->writeInt32(ntohl(s->sin_addr.s_addr));
41 p->writeInt32(static_cast<int32_t>(ntohs(s->sin_port)));
42 } break;
43
44 case AF_INET6: {
45 const struct sockaddr_in6* s =
46 reinterpret_cast<const struct sockaddr_in6*>(addr);
47 const int32_t* a =
48 reinterpret_cast<const int32_t*>(s->sin6_addr.s6_addr);
49 p->writeInt32(AF_INET6);
50 p->writeInt32(ntohl(a[0]));
51 p->writeInt32(ntohl(a[1]));
52 p->writeInt32(ntohl(a[2]));
53 p->writeInt32(ntohl(a[3]));
54 p->writeInt32(static_cast<int32_t>(ntohs(s->sin6_port)));
55 p->writeInt32(ntohl(s->sin6_flowinfo));
56 p->writeInt32(ntohl(s->sin6_scope_id));
57 } break;
58 }
59}
60
61void deserializeSockaddr(const Parcel* p, struct sockaddr_storage* addr) {
Mark Salyzynd6579cc2014-04-10 09:37:52 -070062 memset(addr, 0, sizeof(*addr));
Mike J. Chen951bd8d2011-08-15 11:59:47 -070063
64 addr->ss_family = p->readInt32();
65 switch(addr->ss_family) {
66 case AF_INET: {
67 struct sockaddr_in* s =
68 reinterpret_cast<struct sockaddr_in*>(addr);
69 s->sin_addr.s_addr = htonl(p->readInt32());
70 s->sin_port = htons(static_cast<uint16_t>(p->readInt32()));
71 } break;
72
73 case AF_INET6: {
74 struct sockaddr_in6* s =
75 reinterpret_cast<struct sockaddr_in6*>(addr);
76 int32_t* a = reinterpret_cast<int32_t*>(s->sin6_addr.s6_addr);
77
78 a[0] = htonl(p->readInt32());
79 a[1] = htonl(p->readInt32());
80 a[2] = htonl(p->readInt32());
81 a[3] = htonl(p->readInt32());
82 s->sin6_port = htons(static_cast<uint16_t>(p->readInt32()));
83 s->sin6_flowinfo = htonl(p->readInt32());
84 s->sin6_scope_id = htonl(p->readInt32());
85 } break;
86 }
87}
88
89} // namespace android