Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion example/get_resource_multicast.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,22 @@
*/

import 'dart:async';
import 'dart:io';
import 'package:coap/coap.dart';

FutureOr<void> main() async {
final uri = Uri.parse('coap://${MulticastAddress.allNodesLinkLocalIPV6}');
final iface = Platform.environment['COAP_IFACE'];
final uri =
iface == null
? Uri.parse('coap://${MulticastAddress.allCOAPNodesLinkLocalIPV6}')
: Uri.parse(
'coap://[${MulticastAddress.allCOAPNodesLinkLocalIPV6.address}%$iface]',
);
final client = CoapClient(uri);

try {
final request = CoapRequest.get(Uri(path: '/.well-known/core'));
request.token = CoapConstants.emptyToken;

await for (final response in client.sendMulticast(request)) {
print(response.payloadString);
Expand Down
8 changes: 6 additions & 2 deletions lib/src/coap_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -661,12 +661,16 @@ class CoapClient {
final String host,
final InternetAddressType addressType,
) async {
final parsedAddress = InternetAddress.tryParse(host);
final decodedHost = Uri.decodeComponent(host);
final parsedAddress = InternetAddress.tryParse(decodedHost);
if (parsedAddress != null) {
return parsedAddress;
}

final addresses = await InternetAddress.lookup(host, type: addressType);
final addresses = await InternetAddress.lookup(
decodedHost,
type: addressType,
);
if (addresses.isNotEmpty) {
return addresses.first;
}
Expand Down
38 changes: 38 additions & 0 deletions lib/src/network/coap_network_udp.dart
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,44 @@ class CoapNetworkUDP implements CoapINetwork {

// Use port 0 to generate a random source port
_socket = await RawDatagramSocket.bind(bindAddress, 0);
_socket!.multicastLoopback = false;

if (address.isMulticast) {
final iface = await _findInterfaceFor(address);
if (iface != null) {
_socket!.setRawOption(
RawSocketOption.fromInt(
RawSocketOption.levelIPv6,
RawSocketOption.IPv6MulticastInterface,
iface.index,
),
);
_socket!.joinMulticast(address, iface);
} else {
_socket!.joinMulticast(address);
}
}
}

Future<NetworkInterface?> _findInterfaceFor(
final InternetAddress multicastAddress,
) async {
final zoneIndex = multicastAddress.address.split('%');
if (zoneIndex.length != 2) {
return null;
}

final ifaceName = zoneIndex.last;
final interfaces = await NetworkInterface.list(
type: InternetAddressType.any,
includeLinkLocal: true,
);

try {
return interfaces.firstWhere((final i) => i.name == ifaceName);
} on StateError {
return null;
}
}

void _receive() {
Expand Down