allentando
allentando

Reputation: 105

Socket programming using Windows 10 and C (Visual Studio 2015)

I wrote socket server code using windows 10 and C (visual studios 2015) but I think bind or listen code is wrong.

When I execute my code, It doesn't wait until client is connected. It is finished after print out "winsock initialization success" and "creating socket success".

Help me please.


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

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

    WSADATA wsaData;

    struct sockaddr_in address_of_server;
    struct sockaddr_in address_of_client;

    int socket_of_client;
    int size_of_address_of_client = sizeof(address_of_client);

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0) {
        printf("winsock initialization success\n");
    }
    else {
        printf("winsock initialization failure\n");
    }

    SOCKET socket_of_server = socket(AF_INET, SOCK_STREAM, 0);

    if (socket_of_server == -1) {
        printf("creating socket failure\n");
    }
    else {
        printf("creating socket success\n");
    }

    memset(&address_of_server, 0, sizeof(address_of_server));
    address_of_server.sin_family = AF_INET;
    address_of_server.sin_addr.s_addr = htonl(INADDR_ANY);
    address_of_server.sin_port = htons(atoi(10000));

    bind(socket_of_server, (struct sockaddr*)&address_of_server, sizeof(address_of_server));

    listen(socket_of_server, 5);

    socket_of_client = accept(socket_of_server, (struct sockaddr*)&address_of_client, &size_of_address_of_client);

    WSACleanup();

}

Upvotes: 0

Views: 2022

Answers (1)

Sami Sallinen
Sami Sallinen

Reputation: 3496

After listen() you need to call accept() to get a new connected socket. listen() just starts the listening and does not wait for any client to connect.

Upvotes: 2

Related Questions