Sockets Problem C++

This is a discussion on Sockets Problem C++ within the Windows Programming forums, part of the Platform Specific Boards category; Hey all, I'm making a quick wrapper in C++ using the WinSock2.h header file. It compiles fine, however for a ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Location
    USA::Colorado
    Posts
    155

    Sockets Problem C++

    Hey all,

    I'm making a quick wrapper in C++ using the WinSock2.h header file. It compiles fine, however for a server, it fails to listen for a connection. It just connects to nothing and grabs the information I ask (random bits from memory). I've tried using a bunch of different ports.

    Here's my code:

    CSocket.h
    Code:
    #pragma once
    
    #pragma comment(lib, "ws2_32.lib")
    
    #include <iostream>
    //#include <string>
    #include <WinSock2.h>
    
    using namespace std;
    
    class CSocket {
    protected:
    	WSADATA wsaData;
    	SOCKET skt, clientSkt;
    	sockaddr_in address;
    
    public:
    	CSocket();
    	~CSocket();
    
    	bool SendData (char*);
    	bool RecieveData (char*, int);
    	void CloseConnection();
    };
    
    class CServerSocket : public CSocket {
    public:
    	void Listen(int);
    
    protected:
    	void Start(int);
    };
    
    class CClientSocket : public CSocket {
    public:
    	void Connect(char*, int);
    };
    CSocket.cpp
    Code:
    #include "CSocket.h"
    
    CSocket::CSocket() {
    	if (WSAStartup(MAKEWORD(2,0), &wsaData) != NO_ERROR) {
    		cerr << "WSAStartup Failed" << endl;
    		WSACleanup();
    		exit(10);
    	}
    
    	skt = socket(AF_INET, SOCK_STREAM, 0);
    
    	if (skt == INVALID_SOCKET || skt == SOCKET_ERROR) {
    		cerr << "Failed to create socket" << endl;
    		WSACleanup();
    		exit(11);
    	}
    }
    
    CSocket::~CSocket() {
    	WSACleanup();
    }
    
    bool CSocket::SendData(char * buff) {
    	send(skt, buff, strlen(buff), 0);
    	cout << "Packet sent. Contains " << strlen(buff) << " bytes of data" << endl;
    	return true;
    }
    
    bool CSocket::RecieveData(char * buff, int size) {
    	int i = recv(skt, buff, size, 0);
    	buff[i] = '\0';
    	cout << "Packet recieved. Contains " << strlen(buff) << " bytes of data" << endl;
    	return true;
    }
    
    void CSocket::CloseConnection() {
    	closesocket(skt);
    }
    
    
    
    void CServerSocket::Listen(int port) {
    	Start(port);
    	while (listen(skt, SOMAXCONN) == SOCKET_ERROR);
    
    	accept(clientSkt, NULL, NULL);
    
    	cout << "Connected";
    }
    
    void CServerSocket::Start(int port) {
    	address.sin_family = AF_INET;
    	address.sin_addr.s_addr = INADDR_ANY;
    	address.sin_port = htons(port);
    
    	if (bind(skt, (SOCKADDR*) &address, sizeof(address)) == SOCKET_ERROR) {
    		cerr << "Socket failed to connect" << endl;
    		WSACleanup();
    		exit(14);
    	}
    }
    
    void CClientSocket::Connect(char * ip, int port) {
    	address.sin_family = AF_INET;
    	address.sin_addr.s_addr = inet_addr(ip);
    	address.sin_port = htons(port);
    
    	if (connect(skt, (SOCKADDR*) &address, sizeof(address)) == SOCKET_ERROR) {
    		cerr << "Socket failed to connect" << endl;
    		WSACleanup();
    		exit(13);
    	}
    
    	cout << "Connected";
    }
    main.cpp
    Code:
    #include <iostream>
    #include "CSocket.h"
    
    int main (void) {
    	cout << "1. host\n2. connect (loopback)\n\noption:";
    
    	CServerSocket s;
    	CClientSocket c;
    
    	int opt;
    	cin >> opt;
    
    	char msg[255];
    
    	if (opt == 1) {
    		s.Listen(1235);
    		s.RecieveData(msg, 254);
    		s.CloseConnection();
    	}
    
    	system("pause");
    
    	return 0;
    }
    Any help on why this is happening would be greatly appreciated.

    Thanks,

    -Matt
    ~guitarist809~

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Well, I don't know how much help this will be to you but here is how I do it (with UDP) in ANSI-C... The example is very incomplete since I'm not about to give away all my secrets However you can see how to open a port, wait till it's not busy before sending, receive datagrams asynchronously using a thread, and how to shut things down when you're done....

    Code:
    /////////////////////////////////////////////////////////////////////////////////////////
    // LAN status
    
    // quick check network status
    BOOL CheckNetwork(void)
      { DWORD ct;
        return IsNetworkAlive(&ct) & (GetLastError() == 0); }
    
    
    // wait until network is connected
    BOOL WaitNetwork(BYTE Tries,BYTE Delay)
      { BYTE  rt = 0; // retry count
        while (!CheckNetwork())
          { if (++rt > Tries)
              return 0;
            Sleep(Delay * 1000); }
        return 1; }
    
    
    /////////////////////////////////////////////////////////////////////////////////////////
    // send datagrams
    //
    
    // compose and send datagrams
    BOOL SendDatagram(PSOCKADDR To,DWORD PassCode,BYTE Command,PVOID Data,INT DataSize)
      { DATAGRAM  dgram = {0};  // blank datagram
        INT       sdgram;       // datagram size
        FD_SET    st;           // socket to be tested
        TIMEVAL   tv;           // delay time for test
        // insert passcode
        dgram.PassCode = PassCode;
        // insert command
        dgram.Command = Command;           
        // copy data
        if (DataSize > 0)
          memcpy(&dgram.Data,Data,DataSize);
        // calculate size
        sdgram = ((DWORD)&dgram.Data - (DWORD)&dgram) + DataSize + sizeof(TCHAR); 
        // wait then send
        st.fd_count    = 1;
        st.fd_array[0] = hSocket;
        tv.tv_sec      = 5;
        tv.tv_usec     = 0;
        if (select(1,NULL,&st,NULL,&tv) > 0)
          if (sendto(hSocket,(PCHAR)&dgram,sdgram,0,To,sizeof(SOCKADDR)) > 0)
            return 1;
        return 0; }
    
    /////////////////////////////////////////////////////////////////////////////////////////
    // Receive Datagrams
    //
    
    // datagram tosser prototype
    BOOL CALLBACK (*Toss)(PSOCKADDR,DWORD,BYTE,LPVOID);
    
    // receiver thread 
    DWORD Listener(LPVOID DgramTosser)
      { DATAGRAM  dgram;          // blank datagram 
        INT       sdg;            // size of datagram
        SOCKADDR  from;           // return address
        INT       sf;             // size of reply addr     
        // set callback
        Toss = DgramTosser;
        // receiver loop
        while(!KillWSA)
          { // clear old data
            memset(&dgram,0,sizeof(DATAGRAM));
            // set address size
            sf = sizeof(SOCKADDR);
            // receive datagram
            sdg = recvfrom(hSocket,(PCHAR)&dgram,sizeof(DATAGRAM),0,&from,&sf);
            // hand to tosser
            if (sdg > 0)
              { Toss(&from,dgram.PassCode,dgram.Command,&dgram.Data); } }
        return WSAGetLastError(); }
    
    
    
    // resolve server name and port to useable LAN addr
    BOOL GetHostAddr(PTCHAR Name, WORD Port, PSOCKADDR Addr, BYTE Tries, BYTE Delay)
      { ADDRINFOT   hints = {0};    // hints for search
        PADDRINFOT  res   = NULL;   // pointer to search result
        BYTE        rt    = 0;      // retry count
        // wait for connection
        WaitNetwork(20,1);
        // fill in struct
        hints.ai_flags    = AI_PASSIVE;
        hints.ai_family   = AF_INET;
        hints.ai_socktype = SOCK_DGRAM;
        hints.ai_protocol = IPPROTO_UDP;
        // get ip address
        while(GetAddrInfo(Name,NULL,&hints,&res))
          { if (++rt > Tries)
              return 0; 
            Sleep(Delay * 1000); }
        // transfer to local IP struct
        memcpy(Addr,res->ai_addr,sizeof(SOCKADDR));
        ((PSOCKADDR_IN) Addr)->sin_family = AF_INET;
        ((PSOCKADDR_IN) Addr)->sin_port = htons(Port);
        // release memory 
        FreeAddrInfo(res);
        return 1; }
    
    
    
    // for incremental port search
    VOID SetHostPort(WORD Port,PSOCKADDR Addr)
      { ((PSOCKADDR_IN) Addr)->sin_port = htons(Port);
        ((PSOCKADDR_IN) Addr)->sin_family = AF_INET; }
    
    
    
    /////////////////////////////////////////////////////////////////////////////////////////
    // start and stop
    //
    
    // initialize Client port/return port number
    WORD InitNetwork(WORD Port,BOOL Scan,LPVOID DgramTosser )
      { WSADATA     wsadata;              // winsock startup
        TCHAR       hn[MAX_HOSTNAME];     // host name
        DWORD       hs = MAX_HOSTNAME;    // host name size
        SOCKADDR    la;                   // local address
        INT         x = 0;                // counter
        ULONG       bl = 0;               // blocking flag
        WORD        lp = Port;            // local port
        // Load the Winsock DLL
        if (WSAStartup(MAKEWORD(2,0),&wsadata))
          return 0;
        // initialize local socket
        hSocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
        if (hSocket == INVALID_SOCKET)
          return 0;
        // set full blocking mode
        ioctlsocket(hSocket,FIONBIO,&bl);
        // initialize localhost IP  
        GetComputerName(hn,&hs);
        if (!GetHostAddr(hn,Port,&la,10,1))
          return 0;
        // bind on user designated Port
        while(bind(hSocket,&la,sizeof(SOCKADDR)))
          { if (!Scan)
              return 0;
            SetHostPort(++lp,&la);
            if (lp > (Port + 256))
              return 0; }
        // launch the listener thread
        KillWSA = FALSE;
        hReceiver = CreateThread(NULL,0,&Listener,DgramTosser,0,NULL); 
        if (hReceiver == NULL)
          return 0;
        return lp; }
    
    
    
    // shut down the network
    VOID KillNetwork(void)
      { //let packets clear
        Sleep(100);
        // stop receiver
        KillWSA = TRUE;
        // teminate the receiver
        TerminateThread(hReceiver,0);
        // close the socket
        shutdown(hSocket,SD_BOTH);
        closesocket(hSocket);
        // let winsock close
        Sleep(100);
        // cleanup handles
        WSACleanup(); 
        CloseHandle(hReceiver); }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Sockets - recv() problem
    By Mercurius in forum Networking/Device Communication
    Replies: 3
    Last Post: 05-15-2006, 07:49 AM
  2. Sockets and UDP problem
    By ally153 in forum C Programming
    Replies: 5
    Last Post: 03-20-2006, 04:19 AM
  3. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 05:24 PM
  4. multiple UDP sockets with select()
    By nkhambal in forum Networking/Device Communication
    Replies: 2
    Last Post: 01-17-2006, 06:36 PM
  5. Replies: 5
    Last Post: 11-07-2005, 10:34 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21