Pierre LAGOUTTE
Pierre LAGOUTTE

Reputation: 101

C++ winsock TCP listening

I have a software that decodes ADS-B messages (from planes) and sends results in hexadecimal to a port (47806).

I would like to listen to this port to show that data, so I wrote this :

WSADATA WSAData;
WSAStartup(MAKEWORD(2, 0), & WSAData);

SOCKET sock;
SOCKADDR_IN socket_in;
socket_in.sin_addr.s_addr = htonl(INADDR_ANY);
socket_in.sin_family = AF_INET;
socket_in.sin_port = htons(47806);
sock = socket(AF_INET, SOCK_STREAM, 0);
bind(sock, (SOCKADDR*)& socket_in, sizeof(socket_in));

listen(sock, 0);
int valid = 0;
while (TRUE) {
    int size_socket_in = sizeof(socket_in);
    valid = accept(sock, (SOCKADDR*)& socket_in, & size_socket_in);

    if (valid != INVALID_SOCKET) {
        std::cout << "OK";
    }
}

This code should display "OK" each time a message is received, but it doesn't. I can read data with a Telnet software, like PuTTY : PuTTY telnet on port 47806

I don't understand why my code doesn't work.

Upvotes: 1

Views: 2618

Answers (1)

Pierre LAGOUTTE
Pierre LAGOUTTE

Reputation: 101

Here's the right code :

WSADATA WSAData;
WSAStartup(MAKEWORD(2, 0), & WSAData);

SOCKET sock;
SOCKADDR_IN socket_in;
InetPton(AF_INET, "127.0.0.1", & socket_in.sin_addr.s_addr);
socket_in.sin_family = AF_INET;
socket_in.sin_port = htons(47806);
sock = socket(AF_INET, SOCK_STREAM, 0);
connect(sock, (SOCKADDR*)& socket_in, sizeof(socket_in));

int valid = 0;
char buffer[512] = "";
while (TRUE) {
    valid = recv(sock, buffer, sizeof(buffer), 0);

    if (valid != INVALID_SOCKET) {
        std::cout << buffer;
    }
}

My program is a client and not a server. So I have to define an IP adress with InetPton, connect to the server with connect and receive the messages with recv.

Thank you @Hasturkun and @RustyX for help and explanations.

Upvotes: 2

Related Questions