Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

pkmk

macrumors newbie
Original poster
Mar 30, 2010
6
0
hi,
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.

Code:
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("192.168.3.5");
    addr.sin_port = htons( 32005 );
	
    addr1.sin_family = AF_INET;
    addr1.sin_addr.s_addr = htonl("192.168.3.5");
    addr1.sin_port = htons( 32005 );
	
	// make address reusable
	int yes=1;
	setsockopt(sockfd,SOL_SOCKET,SO_REUSEPORT,&yes,sizeof(int));
	
    // Bind it to an address and port
    if( bind( sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) )
		printf("\nBind failed\n");
	else 
		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");
	else 
		printf("\nBind 1 success\n");
 
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.
 
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?
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.