Obj-C: How to make UDP packet's Source Port consistent in GCDAsyncUdpSocket? source port alway change

StackOverflow https://stackoverflow.com/questions/17871652

  •  04-06-2022
  •  | 
  •  

Question

I have using following code to crate UDP packets.I using bindToPort to setup Source Port.

[asyncUdpSocket bindToPort:7701
                     error:&socketError])  

However, ! found only first time I go through those codes can get a right source port. Rest times, they are all wrong!! My bind to port should be 7701.

Image captured by Wireshark

 GCDAsyncUdpSocket *asyncUdpSocket;
    asyncUdpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self
                                                   delegateQueue:dispatch_get_main_queue()];
    [asyncUdpSocket setPreferIPv4];
    if ([asyncUdpSocket bindToPort:7701
                             error:&socketError]){
        NSLog(@"Bind to Port fail");
    }
    [asyncUdpSocket enableBroadcast:NO error:&socketError];
    [asyncUdpSocket sendData:data
                      toHost:@"192.168.16.77"
                        port:7701
                 withTimeout:-1
                         tag:0];

Question:

How to make UDP packet's Source Port consistent in GCDAsyncUdpSocket?

Was it helpful?

Solution

The reason of variable port number is I am using ARC. The instance might not be released at next time alloc and init.

Everytime I call this part code I create a new GCDAsyncUdpSocket object, then try to bind the port and then send the message. These objects are being dealloced only at a later time when I use ARC. So, actually I am trying to bind to the port several times which is not possible. Once the port is bound, I cannot bind it any more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top