Int to PCSTR for Winsock DEFAULT_PORT

2.9k views Asked by At

I a menu that displays first thing when running my winsock application, I'd like to be able to choose a port on startup but I am having problems converting int to PCSTR or any other type of conversion as I have tried a few.

Here is some code:

My header file:

char* DEFAULT_PORT = "10187";

My cpp file:

cout << "\n Input port: ";

cin >> UserDefinedPort;

if (UserDefinedPort > 1000){

    char* p = p + UserDefinedPort;

    DEFAULT_PORT = p;

} else {

    // err...

}

Beginning of my sock function:

int SocketAddrInfo(int iResult, addrinfo* MySocket, addrinfo** MySocketResult){

iResult = getaddrinfo(NULL, DEFAULT_PORT, MySocket, MySocketResult);

if (iResult != 0) {

    printf("Get address info failed with error: %d\n", iResult);

    WSACleanup();

    std::cout << "Server closing in 5 ";

    for (int i = 4; i > 0; i--){

        Sleep(1 * 1000);

        cout << i << " ";

    }

    cout << "Server closing now!" << endl;

    return 1;

}

return iResult;

}

It throws read mem errors or some type of kernel.dll error no matter what method I try.

Any help would be great, thanks in advance!

1

There are 1 answers

2
Remy Lebeau On

First off, this line is undefined behavior:

char* p = p + UserDefinedPort;

You are trying to add a number to a pointer, before the pointer is even initialized. Besides, you can't simply add a number to a char* pointer to increment the numeric value that the char* string represents. You would have to convert the string to an integer, then increment it, then convert the result back to a string.

I suggest a different approach. Treat the post as an integer everywhere, and only convert it to a string when calling getaddrinfo(), eg:

unsigned short DEFAULT_PORT = 10187;

unsigned short UserDefinedPort;

cout << "\n Input port: ";
if (cin >> UserDefinedPort)
{
    if (UserDefinedPort > 1000)
        DEFAULT_PORT = UserDefinedPort;
    else
    {
        // err...
    }
}
else
{
    // err...
}

#include <sstream>

int SocketAddrInfo(addrinfo* MySocket, addrinfo** MySocketResult)
{
    std::ostringstream oss;
    oss << DEFAULT_PORT;

    int iResult = getaddrinfo(NULL, oss.str().c_str(), MySocket, MySocketResult);

    //...
}