Use the ifindex directly instead of name to get around android restrictions

This commit is contained in:
Muaz Ahmad 2024-05-17 23:44:53 +05:00
parent e112e65794
commit 1bdcb150b1
2 changed files with 8 additions and 14 deletions

View file

@ -3,13 +3,11 @@ const util = @import("util.zig");
const MDNSError = error{
SocketInitFail,
UDPConnectFail,
UDPSendFail,
UDPRecvFail,
NotResponse,
NoMatchingAddress,
AddressBadFormat,
SocketSetTimeoutFail,
};
pub fn get_mdns(domain: util.Domain, ip_info: util.IPInfo) !util.IP {
@ -41,9 +39,9 @@ fn get_mdns_socket(ip_info: util.IPInfo) !socket {
if (sock == -1) {
return MDNSError.SocketInitFail;
}
const timeout: std.c.timeval = .{ .tv_sec = 1, .tv_usec = 0 };
const timeout: std.c.timeval = .{ .tv_sec = 5, .tv_usec = 0 };
if (std.c.setsockopt(sock, std.c.SOL.SOCKET, std.c.SO.RCVTIMEO, &timeout, @intCast(@sizeOf(std.c.timeval))) == -1) {
return MDNSError.SocketSetTimeoutFail;
return MDNSError.SocketInitFail;
}
return sock;
}
@ -87,7 +85,7 @@ fn get_target_address(ip_info: util.IPInfo) !std.net.Address {
var buf: [50]u8 = undefined;
var byte_buf = std.io.fixedBufferStream(&buf);
const writer = byte_buf.writer();
try std.fmt.format(writer, "ff02::fb%{s}", .{ip_info.interface.?});
try std.fmt.format(writer, "ff02::fb%{d}", .{ip_info.interface});
break :blk buf[0..writer.context.pos];
},
else => unreachable,
@ -181,7 +179,7 @@ fn parse_mdns_response(response: []u8, ip_info: util.IPInfo) !util.IP {
if (ip_bytes[0] == 0xfd) {
var addr_buff: [16]u8 = undefined;
@memcpy(&addr_buff, ip_bytes);
addr = std.net.Address.initIp6(addr_buff, 0, 0, @intCast(std.c.if_nametoindex(ip_info.interface.?)));
addr = std.net.Address.initIp6(addr_buff, 0, 0, @intCast(ip_info.interface));
}
}
}

View file

@ -32,7 +32,7 @@ pub fn merge_addrs(v4: IP, v6: IP) IP {
pub const IPInfo = struct {
version: IP_VER_ENUM,
interface: ?[:0]const u8,
interface: c_int,
};
pub const Domain = struct {
@ -64,14 +64,10 @@ pub fn get_input() !struct {
const ip_ver_str = args.next() orelse return ArgError.NotEnoughArgs;
const ip_ver = std.meta.intToEnum(IP_VER_ENUM, std.fmt.parseInt(u3, ip_ver_str, 10) catch return ArgError.InvalidAddressVer) catch return ArgError.InvalidAddressVer;
var iface: ?[:0]const u8 = null;
if (ip_ver != .IPv4) {
iface = args.next() orelse return ArgError.InterfaceRequired;
if (std.c.if_nametoindex(iface.?) == 0) {
const iface = try std.fmt.parseInt(c_int, args.next() orelse return ArgError.NotEnoughArgs, 10);
if (iface < 0) {
return ArgError.InvalidInterface;
}
}
return .{ domain, IPInfo{ .version = ip_ver, .interface = iface } };
}