How to send a packet via a UDP CFSocket?

前端 未结 2 659
遇见更好的自我
遇见更好的自我 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: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];
        });
    
    }
    

提交回复
热议问题