udp broadcast sendto return -1 and errno code 65

- (void)sendBroadcast {
    unsigned int        wifiInterface;
    int                fd;
    BOOL                success;
    struct sockaddr_in  destAddr;
    NSData *            payloadData;
    ssize_t            bytesSent;

    wifiInterface = if_nametoindex("en0");
    assert(wifiInterface != 0);

    fd = socket(AF_INET, SOCK_DGRAM, 0);
    assert(fd >= 0);

    static const int kOne = 1;
    success = setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &kOne, sizeof(kOne)) == 0;
    assert(success);

    success = setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &wifiInterface, sizeof(wifiInterface)) == 0;
    assert(success);

    memset(&destAddr, 0, sizeof(destAddr));
    destAddr.sin_family = AF_INET;
    destAddr.sin_len = sizeof(destAddr);
    destAddr.sin_addr.s_addr = INADDR_BROADCAST;
    destAddr.sin_port = htons(12345);

    payloadData = [[NSString stringWithFormat:@"%@\r\n", [NSDate date]] dataUsingEncoding:NSUTF8StringEncoding];

    bytesSent = sendto(fd, payloadData.bytes, payloadData.length, 0, (const struct sockaddr *) &destAddr, sizeof(destAddr));
    if (bytesSent >= 0) {
        NSLog(@"success");
    } else {
        int code = errno;
        NSLog(@"error code%d, reason:%s", code, strerror(code));
    }
    success = close(fd) == 0;
    assert(success);
}


I run this code,and output error code:65,rason:no route to host.

I test in these devices and use same router:

device:Iphone 5s ,os:IOS 8 ~ IOS 10.1.1, output: success

device:Iphone 6s ,os:IOS 10.0.2, output: error code:65,reason:no route to host.

device:Iphone 7 ,os:IOS 10.0.1, output: success

device: Iphone 6s, os:IOS 10.1.1,output:error code:65,reason:no route to host.

device:Iphone 6 ,os:IOS 10.1.1, output: success

device:Iphone 6 plus ,os:IOS 10.0.2, output: success

device: Iphone 6s plus, os:IOS 10.1.1,output:error code:65,rason:no route to host.

device: Iphone 7, os:IOS 10.1.1,output:error code:65,rason:no route to host.

But I test in ios simulator, output:success

Replies

I can’t see any obvious reason why this would fail.

device: Iphone 6s plus, os:IOS 10.1.1,output:error code:65,rason:no route to host.

I tested exactly this configuration and it works for me.

Does the Wi-Fi network in question lead to the wider Internet? Or it is some sort of restriction network, like the network provided by some accessory?

If, on the devices that fail, you call

getifaddrs
, do you see an IPv4 address for
en0
?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Wi-Fi can access the Internet. and I try some router(Cisco,Lenvo,XiaoMi and hotspot), the result is same.

I call getifaddrs, Output the results

en0 0.0.0.0 ipv6

en0 192.168.223.70 ipv4


In my code, I use AF_INET, so this is a ipv4.