Reputation: 180
I'm new to winapi(winsocket2). Here is my full code (I can't otherwise as my program does compile however does not seem to work(does not bind a socket-bind function return -1)).
#include<winsock2.h>
#include<ws2tcpip.h>
#include<stdio.h>
#include<iostream>
using namespace std;
WSADATA sData;
SOCKADDR_IN linker;
SOCKET sSocket;
int main()
{
if(WSAStartup(MAKEWORD(2,3),&sData)!=0)
{
cout<<"Cannot startup WINsocket";
return -1;
}
cout<<"\tWINsocket loaded!\n\n";
if(sSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)==INVALID_SOCKET)
{
cout<<"Invalid socket.";
return -1;
}
cout<<"\tSocket loaded!\n\n";
linker.sin_family=AF_INET;
linker.sin_addr.s_addr=INADDR_ANY;
linker.sin_port=htons(3490);
memset( &( linker.sin_zero ), '\0', 8 );
char yes='1';
if( setsockopt( sSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof( yes ) ) == - 1 )
{
perror( "setsockopt" );
exit(1);
}
if(bind(sSocket,(struct sockaddr*)&linker,sizeof(linker))==SOCKET_ERROR)
cout<<"lol";
cout<<"\tSocket succesfully binded!\n\n";
listen(sSocket,10);
}
I tried this, pasting right before if bind
char yes='1';
if( setsockopt( sSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof( yes ) ) == - 1 )
{
perror( "setsockopt" );
exit(1);
}
but this func just prints out setsockopt: No error and quit. thanks for help
Upvotes: 0
Views: 1213
Reputation: 45284
The SO_REUSEADDR
option expects a paramter of type BOOL
, which is a typedef for int
. I suspect passing a char
is causing the problem: setsockopt()
will refuse to assign the option unless the last parameter's size matches the expected size, which is not true in your case (sizeof(char) != sizeof(BOOL)
).
In other words, you can change your code to this:
BOOL yes = 1;
if( setsockopt( sSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof( yes ) ) == - 1 )
{
perror( "setsockopt" );
exit(1);
}
Upvotes: 1
Reputation: 311028
if(sSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)==INVALID_SOCKET)
Parentheses problem. Try this:
if((sSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET)
Upvotes: 1