Solved

WINSOCK PROGRAMMING IN C++

Posted on 2004-10-03
13
17,291 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
wordlen challenge 3 61
Path of Workbook 3 61
Installed softare without GUID 6 66
"Black Box" Testing of Control System Software 2 25
Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
This is about my first experience with programming Arduino.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

920 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now