Line data Source code
1 : /* SPDX-License-Identifier: LGPL-2.1+ */
2 : /***
3 : Copyright © 2014 Intel Corporation. All rights reserved.
4 : ***/
5 :
6 : #include <errno.h>
7 : #include <netinet/in.h>
8 : #include <netinet/ip6.h>
9 : #include <stdio.h>
10 : #include <string.h>
11 : #include <sys/socket.h>
12 : #include <sys/types.h>
13 : #include <unistd.h>
14 : #include <linux/if_packet.h>
15 :
16 : #include "dhcp6-internal.h"
17 : #include "dhcp6-protocol.h"
18 : #include "fd-util.h"
19 : #include "socket-util.h"
20 :
21 0 : int dhcp6_network_bind_udp_socket(int index, struct in6_addr *local_address) {
22 0 : union sockaddr_union src = {
23 : .in6.sin6_family = AF_INET6,
24 0 : .in6.sin6_port = htobe16(DHCP6_PORT_CLIENT),
25 : .in6.sin6_scope_id = index,
26 : };
27 0 : _cleanup_close_ int s = -1;
28 : int r;
29 :
30 0 : assert(index > 0);
31 0 : assert(local_address);
32 :
33 0 : src.in6.sin6_addr = *local_address;
34 :
35 0 : s = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, IPPROTO_UDP);
36 0 : if (s < 0)
37 0 : return -errno;
38 :
39 0 : r = setsockopt_int(s, IPPROTO_IPV6, IPV6_V6ONLY, true);
40 0 : if (r < 0)
41 0 : return r;
42 :
43 0 : r = setsockopt_int(s, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, false);
44 0 : if (r < 0)
45 0 : return r;
46 :
47 0 : r = setsockopt_int(s, SOL_SOCKET, SO_REUSEADDR, true);
48 0 : if (r < 0)
49 0 : return r;
50 :
51 0 : r = bind(s, &src.sa, sizeof(src.in6));
52 0 : if (r < 0)
53 0 : return -errno;
54 :
55 0 : return TAKE_FD(s);
56 : }
57 :
58 0 : int dhcp6_network_send_udp_socket(int s, struct in6_addr *server_address,
59 : const void *packet, size_t len) {
60 0 : union sockaddr_union dest = {
61 : .in6.sin6_family = AF_INET6,
62 0 : .in6.sin6_port = htobe16(DHCP6_PORT_SERVER),
63 : };
64 : int r;
65 :
66 0 : assert(server_address);
67 :
68 0 : memcpy(&dest.in6.sin6_addr, server_address, sizeof(dest.in6.sin6_addr));
69 :
70 0 : r = sendto(s, packet, len, 0, &dest.sa, sizeof(dest.in6));
71 0 : if (r < 0)
72 0 : return -errno;
73 :
74 0 : return 0;
75 : }
|