how to bind two udp socket on same port

Discussion in 'Mac Programming' started by pkmk, Mar 30, 2010.

  1. pkmk macrumors newbie

    Mar 30, 2010
    i have the following code. When i run the code it bind the 2nd socket but not the first socket. It print "Bind failed". How can i bind both socket on same port and ip. Please help me.

    struct sockaddr_in addr;
    struct sockaddr_in addr1;
    int sockfd;
    int sockfd1;
        // Create a socket
        sockfd = socket( AF_INET, SOCK_DGRAM, 0 );
       sockfd1 = socket( AF_INET, SOCK_DGRAM, 0 );
        // Setup its address structure
       // bzero( &addr, sizeof(struct sockaddr_in));
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = htonl("");
        addr.sin_port = htons( 32005 );
        addr1.sin_family = AF_INET;
        addr1.sin_addr.s_addr = htonl("");
        addr1.sin_port = htons( 32005 );
    	// make address reusable
    	int yes=1;
        // Bind it to an address and port
        if( bind( sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) )
    		printf("\nBind failed\n");
    		printf("\nBind success\n");
    	// Bind it to an address and port
        if( bind( sockfd1, (struct sockaddr *)&addr1, sizeof(struct sockaddr)) )
    		printf("\nBind 1 failed\n");
    		printf("\nBind 1 success\n");
  2. jpyc7 macrumors 6502

    Mar 8, 2009
    Denver, CO
    I don't know the answer, but I suggest you learn/use the "netstat -n" command to see if the port is in use. Once you've opened a socket once, the kernel will not necessarily close it immediately when your program exits depending on its type and the options used to create it. For example, TCP sockets have a timeout associated with their protocol.

    Second, I suggest you consider a different design for your program if you're having trouble getting two different sockets on the same port. Learn about the "select" or "poll" unix system calls and use a single socket instead. If you want to use threads, then learn about mutual exclusion locking.

    Third, post complete example test code (within code tags for the forum) that can be easily compiled by others to try. I would've tried to use your code, but I don't want to spend the time figuring out the #includes and write a main routine.
  3. Cromulent macrumors 603


    Oct 2, 2006
    The Land of Hope and Glory
    Firstly if you are in charge of the code for both processes then you need to set SO_REUSEADDR (this is apparently the better option for cross platform compatibility than SO_REUSEPORT) on both sockets, at the moment you have only one call to setsockopt() on one of your sockets.

    SO_REUSEADDR and SO_REUSEPORT are really only useful for multicast clients though as they will both receive the same data sent to the port.

    What is it that you are actually trying to do?

Share This Page