Solved

WINSOCK PROGRAMMING IN C++

Posted on 2004-10-03
13
17,302 Views
Last Modified: 2013-11-13
Hey there...

When i run the below code, all the error checks say it's ok. However when the program gets into the "accept" loop, it loops forever. I CAN connect to that port, (when the program is not running i can NOT connect to that port), however when i send data to that port the program does not acknowledge the data for some reason. I cannot see what i am doing wrong. Source code below.

=========================================================================================

#include "stdafx.h"
#include "windows.h"
#include <iostream>
#include <string>

#include "WINSOCK2.H"
#pragma comment (lib, "WS2_32.LIB")

const UINT cc_port = 3276;

int _tmain(int argc, _TCHAR* argv[])
{
      WSADATA data;
      SOCKET sock, tmp_sock;
      SOCKADDR_IN local_info, remote_info;
      int cLen;

      std::cout << "attempting to initalize... ";
      if(WSAStartup(MAKEWORD(2,2), &data))
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";
      
      std::cout << "attempting to create socket...";
      sock = socket(AF_INET, SOCK_STREAM, 0);

      if(sock == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      local_info.sin_family = AF_INET;
      local_info.sin_port = htons(cc_port);
      local_info.sin_addr.s_addr = htons(INADDR_ANY);
      
      std::cout << "attempting to bind... ";
      if(bind(sock, (SOCKADDR*) &local_info, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      std::cout << "attempting to prepare socket for listening... ";
      if(listen(sock, 5) == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      std::cout << "attempting to listen for a connection";
      do
      {
            tmp_sock = accept(sock, (SOCKADDR*) &remote_info, &cLen);
            std::cout << "!";
      }
      while(tmp_sock == SOCKET_ERROR);
      std::cout << "\nconnection recived!!!!!!!!!!!!!!!";

      closesocket(sock);
      closesocket(tmp_sock);
      WSACleanup();

      getchar();
      return 0;
}

=========================================================================================

Any suggestions would be much appreciated,
SOUTHERN CURRIEZ
0
Comment
Question by:da_mango_bros
  • 4
  • 4
  • 3
  • +1
13 Comments
 
LVL 1

Expert Comment

by:lubovec
ID: 12211150
hi da_mango_bros

you need not use the accept loop, because your socket is in blocked mode. that means function accept is blocking execution of program before connection is recieved. it is not error

try replace this part of code

     do
     {
          tmp_sock = accept(sock, (SOCKADDR*) &remote_info, &cLen);
          std::cout << "!";
     }
     while(tmp_sock == SOCKET_ERROR);
     std::cout << "\nconnection recived!!!!!!!!!!!!!!!";

by this

     tmp_sock = accept(sock, (SOCKADDR*) &remote_info, &cLen);
     std::cout << "!";
     std::cout << "\nconnection recived!!!!!!!!!!!!!!!";

good luck

bye

PS: i hope my english is understandable ;)
0
 
LVL 7

Expert Comment

by:dttri
ID: 12211228
 Hello,
  After you send data to the program, what the program response? It end or whatever?

  Tri
0
 

Author Comment

by:da_mango_bros
ID: 12211357
Hey thanks for replying.

lubovec:

Something seems to be seriously wrong. I removed the loop as you said, but after running it immediately said "connection recived" even though i had not sent anything to that port.

When i had the loop, it just put out long strings of "!" to indicate that each time accept() was failing and immediately being called again.


dttri:

At this stage, i just want it to print the data on the screen and then exit. Before i code any more i want to make sure the basics are working.  

0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 1

Expert Comment

by:lubovec
ID: 12211813

question is, how client are you using to test this server... if you have your own client, try to post its source code...
0
 
LVL 19

Expert Comment

by:drichards
ID: 12212281
Your accept will fail because you have not set cLen properly.  Add 'cLen = sizeof(SOCKADDR_IN);' before the do loop and the accept should work.  Then you will need to add code to recevie the data.
0
 
LVL 7

Accepted Solution

by:
dttri earned 125 total points
ID: 12212591
>>>Your accept will fail because you have not set cLen properly.  Add 'cLen = sizeof(SOCKADDR_IN);' before the do loop and the accept should work.  Then you will need to add code to recevie the data.

That's correct! But if you want to receive data more than 1 times (or in case the first receive fail), but 'cLen=sizeof(SOCKADDR_IN);' at the first line in the loop.
This info is from MSDN:

"SOCKET accept(
  SOCKET s,
  struct SOCK_ADDR* addr,
  int FAR* addrlen
);
The integer referred to by addrlen initially contains the amount of space pointed to by addr. On return, it will contain the actual length in bytes of the address returned."

0
 
LVL 19

Expert Comment

by:drichards
ID: 12212658
>> But if you want to receive data more than 1 times (or in case the first receive fail), but 'cLen=sizeof(SOCKADDR_IN);' at the first line in the loop.
Not really necessary because the returned size will be the same since it will be returning a SOCKADDR_IN.  cLen should not be set on fail.
0
 
LVL 1

Expert Comment

by:lubovec
ID: 12212900

finaly everything is so simple :)
0
 

Author Comment

by:da_mango_bros
ID: 12214177
well i added 'cLen = sizeof(SOCKADDR_IN);', and then it worked fine - there was no need for the loop.

however from dttri's previous comment i think i may still have a problem.

i am trying to make a peer-2-peer chat program, and i need to be able to have more than one connection open at the same time.


so if i just accept the first connection and go ahead and send/recive data, how will i know when someone else is trying to establish a connection with me?

also if i have a continuous loop checking if someone wants to connect, how will i be able to go ahead and send/recive data?
0
 
LVL 7

Assisted Solution

by:dttri
dttri earned 125 total points
ID: 12214459
 Hello,
  If you need your program to be able to accept connection and also send and receive data, you may use multithreaded, for example: your main thread will wait and accept connections, if it receive 1 connection and it will create a new thread to handle this connection.
  You can view the simple source here:
http://tangentsoft.net/wskfaq/examples/basics/threaded-server.cpp
  The code project article about multithreaded TCP server:
http://www.codeproject.com/internet/winsockintro03.asp
  And this discussion may be useful:
http://forums.devshed.com/showthread.php?t=169115

  Tri
0
 

Author Comment

by:da_mango_bros
ID: 12214815
ok thankz i should have no problems making it now
0
 
LVL 7

Expert Comment

by:dttri
ID: 12215266
 Hello,
  Can you request the Mod to split the points to drichards for me? Because he found 'cLen = sizeof(SOCKADDR_IN);' for you.

  Regards,
  Tri
0
 

Author Comment

by:da_mango_bros
ID: 12215611
ahh yes... i missed that before (probably because everyone posted at once and i didnt look at the names).

will request to the mod
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
firstswap challenge 20 82
Problem to open text file 11 128
jboss 7.1 start up error 1 37
C qsort compare function issue 6 17
This is an explanation of a simple data model to help parse a JSON feed
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question