How to send a packet via a UDP CFSocket?

前端 未结 2 660
遇见更好的自我
遇见更好的自我 2021-01-02 11:29

I am a complete newbie to networking, however I am a c/c++ programmer, and am working in objective-c (This is for OSX/iPhone).

I am trying to learn how to send a mag

相关标签:
2条回答
  • 2021-01-02 12:14

    Your problem is very simple: you are not telling the CFSocket where you want it to send the data.

    You carefully construct an address in addr, but then don't use it. You either need to call CFSocketSetAddress to set the destination address on the socket (if you want all packets you send to go to the same destination), or pass the address as the 2nd argument to CFSocketSendData.

    0 讨论(0)
  • 2021-01-02 12:19

    This is my first working bit of code for two whole nights! Hopefully will help someone else! Thought I should share it, might save someone a bit of hassle.

    I disabled the listen call, as I only wanted to send data.

    + (void)broadCast
    {
        int socketSD = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (socketSD <= 0) {
            NSLog(@"Error: Could not open socket.");
            return;
        }
    
        // set socket options enable broadcast
        int broadcastEnable = 1;
        int ret = setsockopt(socketSD, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));
        if (ret) {
            NSLog(@"Error: Could not open set socket to broadcast mode");
            close(socketSD);
            return;
        }
    
        // Configure the port and ip we want to send to
        struct sockaddr_in broadcastAddr;
        memset(&broadcastAddr, 0, sizeof(broadcastAddr));
        broadcastAddr.sin_family = AF_INET;
        inet_pton(AF_INET, "255.255.255.255", &broadcastAddr.sin_addr);
        broadcastAddr.sin_port = htons(33333);
    
        char *request = "message from ios by c";
        ret = sendto(socketSD, request, strlen(request), 0, (struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr));
        if (ret < 0) {
            NSLog(@"Error: Could not open send broadcast.");
            close(socketSD);
            return;
        }
    
        close(socketSD);
    
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            //[self listenForPackets];
        });
    
    }
    
    0 讨论(0)
提交回复
热议问题