So uhh... Whenever I run this network program listen isn't blocking properly. It's not waiting for incoming connections, it's just instantly going down to accept(), and accept() is returning an error... I have no idea why listen() isn't blocking. I ran this program by itself (with no interacting client program running) and that is what it does. Output:
Listening on socket...
ERROR.
If I replace printf("ERROR."); with perror("ERROR."); it says:
Listening on socket...
ERROR. No error found
But that doesn't really make sense because it wouldn't be going through the if statement if there was no error, it will only go through the if statement if the accept call returns INVALID_SOCKET. Ok here is the code:
Code:
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <cstring>
#include <Mstcpip.h>
#define MYPORT "3490"
#define BACKLOG 10
using std::cout;
using std::cin;
using std::endl;
WSADATA wsaData;
int main(int argc, char * argv[]) {
int wsaReturnVal = WSAStartup(MAKEWORD(1, 1), &wsaData);
if (wsaReturnVal) {
cout << "Error number: " << wsaReturnVal << endl;
exit(1);
}
struct addrinfo hints, *res = NULL;
struct sockaddr_storage *their_addr;
SOCKET sockfd, newfd = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_flags = AI_PASSIVE;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo(NULL, MYPORT, &hints, &res);
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (bind(sockfd, res->ai_addr, res->ai_addrlen) == -1) {
printf("Socket bind error.");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
printf("Socket listen error.");
exit(1);
}
printf("Listening on socket...\n");
closesocket(sockfd);
int addr_size = sizeof(their_addr);
if ((newfd = accept(newfd, (struct sockaddr *)&their_addr, &addr_size)) == INVALID_SOCKET) {
printf("ERROR.");
closesocket(newfd);
exit(1);
}
char buffer[255];
recv(newfd, buffer, 255, 0);
send(newfd, buffer, 255, 0);
freeaddrinfo(res);
if (WSACleanup()) {
cout << "Cleanup Error." << endl;
exit(1);
}
}
Thanks!