简体   繁体   中英

winsock2 cannot bind a socket

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

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);
}
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM