C++ blank console after WSAStartup

149 views Asked by At

I'm very new to C++ and am having some trouble setting up a simple UDP server. All I want my code to do is receive a message and print it to the console.

After a lot of research I found out I needed to use WSAStartup to get the sockets to work correctly, but I am unsure how it works and where to put WSACleanup. If I put WSACleanup after the socket has been created I get returned the error code "10093" in the console when performing the "bind" method. If do not use the cleanup then the program runs and shows nothing in the console at all.

I have gone through the code in debug mode and have found it does seem to run successfully as it will hang on the "recvfrom" line until I send a message using a test UDP java client. I'm just wondering why there isn't anything being printed to the console or if I am missing something.

Any help would be much appreciated. I am using netbeans for my IDE and MinGW compiler as well.

Here is my code:

#include <stdio.h>
#include <windows.h> 
#include <winsock2.h>
#include <ws2tcpip.h>

#define PORT 9760
#define BUFSIZE 1024

void startup()
{  
    WORD wVersionRequested;
    WSADATA wsaData;
    int start;

    wVersionRequested = MAKEWORD(2, 2);
    start = WSAStartup(wVersionRequested, &wsaData);

    if(start!=0){
        printf("This version is not supported! - %d \n", WSAGetLastError());
    }
    else{
        printf("Good - Everything fine!\n");
    }
}

void Server()
{    
    startup();

    struct sockaddr_in myaddr;      
    struct sockaddr_in remaddr;     
    socklen_t addrlen = sizeof(remaddr); 
    int recvlen;     
    SOCKET fd;  
    char buf[BUFSIZE];  


    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("cannot create socket\n");
        return;
    }
    else {
        printf("socket created \n");        
    }

    memset((char *)&myaddr, 0, sizeof(myaddr));
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    myaddr.sin_port = htons(PORT);

    int bindVal = bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr));

    if (bindVal < 0) {
        printf("socket error: %d, %s \n", errno, strerror(errno));
        perror("bind failed");
        printf("bind wsaerr: %d \n", WSAGetLastError());
        WSACleanup();

        return;
    }

    for (;;) {
        //printf("waiting on port %d\n", PORT);
        recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
        //printf("received %d bytes\n", recvlen);
        if (recvlen > 0) {
            buf[recvlen] = 0;
            printf("received message: \"%s\"\n", buf);
        }

        //WSACleanup();
    }

}

int main(int argc, char** argv) {

    Server();

    WSACleanup();

    return 0;
}
0

There are 0 answers