+
+// All sorts of fiddling is needed to set the source address for UDP
+// And 2 different ways for pure ipv4 versus ipv6 sockets
+static void sendpacket4(unsigned char *buf, int n,struct Remote *r) {
+ // The UDP socket is pure ipv4
+ struct iovec data[1] = {{ .iov_base = buf, .iov_len = n }};
+ struct {
+ struct cmsghdr hdr;
+ struct in_pktinfo data;
+ } control = {
+ .hdr.cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)),
+ .hdr.cmsg_level = IPPROTO_IP,
+ .hdr.cmsg_type = IP_PKTINFO,
+ .data.ipi_ifindex = r->ifindex,
+ .data.ipi_spec_dst = r->laddr.in4.sin_addr
+ };
+ struct msghdr msg = {
+ .msg_name = &r->uaddr.in4,
+ .msg_namelen = sizeof( struct sockaddr_in ),
+ .msg_iov = data,
+ .msg_iovlen = 1,
+ .msg_control = &control,
+ .msg_controllen = CMSG_SPACE( sizeof( struct in_pktinfo ) ),
+ .msg_flags = 0 // unused
+ };
+ VERBOSE2OUT( "sendmsg ipv4 %lu from %s to %s\n",
+ msg.msg_controllen,
+ inet_stoa( &r->laddr ),
+ inet_stoa( &r->uaddr ) );
+ if ( sendmsg( udp_fd, &msg, 0 ) < n ) {
+ perror( "Writing socket" );
+ }
+}
+
+static void sendpacket6(unsigned char *buf, int n,struct Remote *r) {
+ // The UDP socket is ipv6, possibly with mapped ipv4 address(es)
+ struct iovec data[1] = {{ .iov_base = buf, .iov_len = n }};
+ struct {
+ struct cmsghdr hdr;
+ union {
+ struct in_pktinfo in4;
+ struct in6_pktinfo in6;
+ } data;
+ } control;
+ struct msghdr msg = {
+ .msg_name = &r->uaddr.in6,
+ .msg_namelen = sizeof( struct sockaddr_in6 ),
+ .msg_iov = data,
+ .msg_iovlen = 1,
+ .msg_control = 0,
+ .msg_controllen = 0,
+ .msg_flags = 0 // unused
+ };
+ if ( r->ifindex ) {
+ switch ( r->laddr.in.sa_family ) {
+ case AF_INET6:
+ control.hdr.cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
+ control.hdr.cmsg_level = IPPROTO_IPV6;
+ control.hdr.cmsg_type = IPV6_PKTINFO;
+ control.data.in6.ipi6_ifindex = r->ifindex;
+ memcpy( &control.data.in6.ipi6_addr, &r->laddr.in6.sin6_addr, 16 );
+ msg.msg_control = &control;
+ msg.msg_controllen = CMSG_SPACE( sizeof( struct in6_pktinfo ) );
+ break;
+ case AF_INET:
+ control.hdr.cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
+ control.hdr.cmsg_level = IPPROTO_IP;
+ control.hdr.cmsg_type = IP_PKTINFO;
+ control.data.in4.ipi_ifindex = r->ifindex;
+ control.data.in4.ipi_spec_dst = r->laddr.in4.sin_addr;
+ msg.msg_control = &control;
+ msg.msg_controllen = CMSG_SPACE( sizeof( struct in_pktinfo ) );
+ break;
+ }
+ }
+ VERBOSE2OUT( "sendmsg ipv6 %d from %s to %s\n",
+ r->ifindex,
+ inet_stoa( &r->laddr ),
+ inet_stoa( &r->uaddr ) );
+ if ( sendmsg( udp_fd, &msg, 0 ) < n ) {
+ perror( "Writing socket" );
+ }
+}
+