user2626734
user2626734

Reputation: 26

Whats wrong with my server code(c++)

I am almost finished making this server but before I finished it I wanted to test it, but when I do it keeps on saying "connection was reached" before anyone connects to it. I want it to say, "connection was reached" when someone actually connects to it. any help?

#pragma comment(lib, "Ws2_32.lib")
#include<iostream>
#include<WinSock2.h>

using namespace std;

int main()
{

   WSAData wsa;

   int iresult =WSAStartup(MAKEWORD(2,1), &wsa);

   SOCKADDR_IN Server;

   Server.sin_addr.s_addr=inet_addr("127.0.0.1");

   Server.sin_family = AF_INET;

   Server.sin_port = 6667;

   SOCKET Listen =(AF_INET,SOCK_STREAM,NULL);

   listen (Listen, SOMAXCONN);

   bind(Listen,(SOCKADDR*)&Server,sizeof(Server));

   SOCKET Connect =(AF_INET,SOCK_STREAM,NULL);

   int size = sizeof(Server);

   std::cout<<"Waiting for connections";

   for(;;)
   {
    if(Connect=accept(Listen,(SOCKADDR*)&Server,&size)) {
        std::cout<<"connection was reached";
        break;
        }
    }


  WSACleanup();

  cin.get();

  return 0;
}

Upvotes: 0

Views: 77

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409442

One problem is here:

Server.sin_port = 6667;

The port number must be in network byte order, which is opposite of the byte order of the common x86 platform. Instead do

Server.sin_port = htons(6667);

There are also many other problems with your code, like for example the ones pointed out in the comment by Joachim Isaksson.

There is also this:

if(Connect=accept(Listen,(SOCKADDR*)&Server,&size))

You have to remember that accept returns SOCKET_ERROR (or -1) on error, which is "true"

Upvotes: 2

Related Questions