Reputation: 1700
I get the error "unable to bind socket" , Error : 10038, An operation was attempted on something that was not a socket. the socket gets created, but I cannot bind it.
struct sockaddr_in serverAddress ; // declared as global
struct sockaddr_in clientAddress ; // declared as global
int len=sizeof(struct sockaddr); // declared as global
SOCKET s = NULL ; // declared as global
memset (& serverAddress , 0 , sizeof ( serverAddress ));
serverAddress.sin_family = AF_UNSPEC ;
serverAddress.sin_addr.s_addr =INADDR_ANY;
serverAddress.sin_port = htons(12345);
if( s = socket(PF_INET,SOCK_DGRAM, IPPROTO_UDP) == INVALID_SOCKET)
{
printf (" Unable to create a socket \n");
printf (" Failed with error : %d\n%s\n", WSAGetLastError () ,
gai_strerror ( WSAGetLastError ()));
exit (1);
}
else
{
std::cout<<"CREATED"<<std::endl;
}
if( bind(s,(struct sockaddr *)&serverAddress,sizeof(serverAddress)) < 0)
{
printf (" Unable to bind socket \n");
printf (" Failed with error : %d\n%s\n", WSAGetLastError () ,
gai_strerror ( WSAGetLastError ()));
}
else
{
printf (" Bound to socket .\n");
}
Upvotes: 2
Views: 3084
Reputation: 5766
You need to fix this line:
if( s = socket(PF_INET,SOCK_DGRAM, IPPROTO_UDP) == INVALID_SOCKET)
The equality operator (==
) is getting executed first, so it creates a socket and checks if it is invalid. However, it never assigns the socket information to s
. Rather, it assigns the boolean result of the equality test, meaning s
is probably set to 0
.
You either need to put parentheses in to correct the order of execution, or simply move the assignment into a separate statement. I'd recommend the latter, for sake of readability:
s = socket(PF_INET,SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
...
It's worth noting that your compiler is probably giving you a warning about that line. It might be saying something like "assignment within conditional expression". You generally shouldn't ignore warnings, because they can help you catch subtle mistakes like this.
Upvotes: 1
Reputation: 310903
Parenthesis problem.
if( s = socket(PF_INET,SOCK_DGRAM, IPPROTO_UDP) == INVALID_SOCKET)
should be
if((s = socket(PF_INET,SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET)
In your code 's' is either 0 or 1 after your line.
Upvotes: 4
Reputation: 1700
this does not assigns to s , therefore I never get a socket number
if( s = socket(PF_INET,SOCK_DGRAM, IPPROTO_UDP) == INVALID_SOCKET)
{
}
this is the correct way
s = socket(PF_INET,SOCK_DGRAM, IPPROTO_UDP);
if( s == INVALID_SOCKET )
{
echo "error";
}
Upvotes: 0