socket bind fails second time round

Nov 3, 2010 at 6:41pm
I have the following code that I use to receive UDP data.

It is in a function that i call every now and again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   char recvbuf[1024];
   int iResult = 1;
   int recvbuflen = 1024;

   sockaddr sdfg;
   sockaddr_in serverAddr;		
   sockaddr_in myAddr;
   int senderAddrSize = sizeof(serverAddr);

   myAddr.sin_family = AF_INET ;
   myAddr.sin_port = htons ( data.udp_port );
   myAddr.sin_addr.s_addr = htonl(INADDR_ANY);
   int socketId = socket (AF_INET , SOCK_DGRAM, IPPROTO_UDP );

   if (bind(socketId, (SOCKADDR *)&myAddr, sizeof(myAddr)) != SOCKET_ERROR)
   {
      iResult = recvfrom(socketId, recvbuf, recvbuflen, 0,(SOCKADDR *)  
                &serverAddr, &senderAddrSize);
      //blah blah
     
   
   }



The fitst time I call it it works fine, but the next time I call it, it fails on this line:
if (bind(socketId, (SOCKADDR *)&myAddr, sizeof(myAddr)) != SOCKET_ERROR)
A -1 is returned.

What do I need to do to fix this?

Cheers
Nov 3, 2010 at 7:04pm
You cannot bind the same ip/udp port to two different sockets at the same time.

In order to call this function a second time, you will need to close the first socket
(I don't know if you omitted that part in the //blah blah).

Otherwise, print out the value of errno after the call to bind to see what the actual
error was.
Nov 3, 2010 at 7:18pm
re:you will need to close the first socket
I have now done this at the bottom:
shutdown(socketId,0);

is this the proper way to close the socket? Because the bind is still failing.

re:print out the value of errno
How do I get this value?
Nov 3, 2010 at 8:10pm
close( socketId );

to close the socket.

to get errno:

#include <errno.h>

std::cout << errno << std::endl;
Nov 4, 2010 at 9:33am
when I do:
close( socketId );

I get:
error C3861: 'close': identifier not found

My project is an MFC project.
Nov 4, 2010 at 9:43am
closesocket(socketId) works for me.

Cheers
Nov 4, 2010 at 1:31pm
yeah, sorry, I only know the posix calls.
Topic archived. No new replies allowed.