Search code examples
c++socketstcpudpudpclient

Unable to call function in main (Inheritance in UDP Client App using C++)


I have created a separate UDP Server Application and a Client Application, and they are communicating with each other. I have tried to implement inheritance as the next step for this application (Base class : udp, child class: udpClient). I have developed the code for the client which I have presented my code below with comments as explanation.

I am having a problem in the last line of the code where the object is used to call the derived class. I do not know what parameters to give here. I have highlighted the problem area with comments. Any help is appreciated

EDIT : Also, 50003 is the port number right? If it was around 70000, the check should give an error right? But its not. What would be the problem?

UDP Client program

#include <iostream>
#include <WS2tcpip.h>

#pragma comment (lib, "ws2_32.lib")

using namespace std;

class udp {

protected:
    WSADATA data;
    WORD version = MAKEWORD(2, 2);

    int wsOk = WSAStartup(version, &data);

public:
    void checkudp()
    {
        if (wsOk != 0)
        {
            cout << "Can't start Winsock! " << wsOk;
            return;
        }
    }

};

class udp_client : public udp {

private:
    sockaddr_in server;
    char clientIp[256];
    int argc;
    char* argv[];

public:
    void udpworking(*int argc, char* argv[]*) { //PROBLEM HERE with call to main function
        
        server.sin_family = AF_INET; // AF_INET = IPv4 addresses
        server.sin_port = htons(50003); // Little to big endian conversion
        inet_pton(AF_INET, "127.0.0.1", &server.sin_addr); // Convert from string to byte array

        // Socket creation, note that the socket type is datagram
        SOCKET out = socket(AF_INET, SOCK_DGRAM, 0);

        // Write out to that socket
        string s(argv[1]);
        int sendOk = sendto(out, s.c_str(), s.size() + 1, 0, (sockaddr*)&server, sizeof(server));

        if (sendOk == SOCKET_ERROR)
        {
            cout << "That didn't work! " << WSAGetLastError() << endl;
        }
        closesocket(out);
        WSACleanup();
    }
};
void main()
{
    udp_client obj;
    obj.udpworking(); //Parameter problem with function call
}

Solution

  • udp_client::udpworking requires two arguments, that you need to pass in parameters (in the parenthesis).

    Also as mentioned in the comments void main() is not a valid signature for this function. Only int main() (which ignores all parameters) and int main(int argc, char **argv) (which takes in the command line parameters) are valid signatures.

    Try something like this:

    int main(int argc, char **argv) {
        udp_client obj;
        obj.udpworking(argc, argv);
        return 0;
    }
    

    PS: I take it you added the stars surrounding the parameters in the functions when you posted it on SO? (the udpworking(*int argc, char* argv[]*))