getaddrinfo() does not translate a hostname into an IP address and consequently does not connect() to the server. Is something wrong with my implementation - compiles with no warning messages?
Is this function call to connect correct?
connect(client, result->ai_addr, result->ai_addrlen)
Full implementation listed below:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
int main (
int argc,
char* argv[])
{
if (argc != 3)
{
cerr << "Usage: " << argv[0] << " [hostname] [port number]\n";
exit(EXIT_FAILURE);
}
WSADATA wsaData;
WORD wVersionRequested;
int wError;
wVersionRequested = MAKEWORD(2, 2);
wError = WSAStartup(wVersionRequested, &wsaData);
if (wError != 0)
{
cerr << "WSAStartup failed with error: " << wError << endl;
exit (EXIT_FAILURE);
}
/*
* Confirm that the WinSock DLL supports 2.2.
* Note that if the DLL supports versions greater
* than 2.2 in addition to 2.2, it will still return
* 2.2 in wVersion since that is the version we
* requested.
*/
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
cerr << "Could not find a usable version of Winsock.dll." << endl;
WSACleanup();
exit(EXIT_FAILURE);
} else {
cout << "The Winsock 2.2 dll was found." << endl;
}
SOCKET client;
if ((client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == SOCKET_ERROR)
{
cerr << "Error: socket() return value == SOCKET_ERROR" << endl;
WSACleanup();
exit (EXIT_FAILURE);
}
cout << "Created a socket." << endl;
struct addrinfo *result = NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if ((wError = getaddrinfo(
argv[1],
argv[2],
&hints,
&result)) !=0 )
{
freeaddrinfo(result);
WSACleanup();
if (wError == 11001)
{
cerr << "Error: occurred: getaddrinfo() failed "
<< wError << " - Host not found." << endl;
exit(EXIT_FAILURE);
}
cerr << "Error: occurred: getaddrinfo() failed "
<< wError << endl;
exit(EXIT_FAILURE);
}
/*
* Attempt to connect to the Server
*
*/
switch (wError = connect(client, result->ai_addr, result->ai_addrlen)) {
case 0:
cerr << "Resolved hostname." << endl;
break;
case SOCKET_ERROR:
wError = WSAGetLastError();
cerr << "Error: connet() failed "
"Details: " << wError << endl;
closesocket(client);
freeaddrinfo(result);
WSACleanup();
exit(EXIT_FAILURE);
break;
default:
cerr << "Fatal connect() error: unexpected "
"return value." << endl;
closesocket(client);
freeaddrinfo(result);
WSACleanup();
exit(EXIT_FAILURE);
break;
}
cout << "Connected to server." << endl;
closesocket(client);
freeaddrinfo(result);
WSACleanup();
exit(EXIT_SUCCESS);
}
getaddrinfo may be giving you an IPv6 address, or perhaps the machine has more than one IP address and you're trying to connect to the wrong one.
Also, if your server is listening on 127.0.0.1 and you try to connect to the real IP address, the connection will fail. Similarly, if the server is listening on the real IP address and you try to connect using 127.0.0.1, the connection will fail. If the server listens on 0.0.0.0, both addresses should work.
To listen on 0.0.0.0, you would have code similar to this:
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port=htons( port_num );
bind( s, (sockaddr *)&sin, sizeof( sin ) );
Try setting the hint.ai_family to AF_UNSPEC instead of AF_INET, I believe that when AF_INET is specfied the getaddrinfo functions excepts IPv4-like address.
Related
I'm trying to construct a simple UDP network program in C++ to establish a real-time data communication platform between two computers in my company.
The below code is for Server (receiver), and I successfully tested the network self-communication (IP='127.0.0.1').
However, if I change the IP number corresponding to another computer (147.47.42.50), I face a binding failure error.
When I type 'ping' in cmd, it successfully returns responses.
Is there any incorrect logic in my program? and is there any way to debug this problem?
#include <stdio.h>
#include <iostream>
#include <winsock2.h>
#include <windows.h>
#pragma comment (lib,"ws2_32.lib")
#define BUFFER_SIZE 1024
using namespace std;
void main(void)
{
WSADATA wsaData;
SOCKET ServerSocket;
SOCKADDR_IN ServerInfo;
SOCKADDR_IN FromClient;
int FromClient_Size;
int Recv_Size;
int Send_Size;
int Count;
char Buffer[BUFFER_SIZE];
short ServerPort = 6000;
if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR)
{
cout << "WinSock initialization fail. " << endl;
WSACleanup();
}
memset(&ServerInfo, 0, sizeof(ServerInfo));
memset(&FromClient, 0, sizeof(FromClient));
memset(Buffer, 0, BUFFER_SIZE);
ServerInfo.sin_family = AF_INET;
ServerInfo.sin_addr.s_addr = inet_addr("147.47.42.50");
ServerInfo.sin_port = htons(ServerPort);
ServerSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (ServerSocket == INVALID_SOCKET) //
{
cout << "Cannot create socket." << endl;
closesocket(ServerSocket);
WSACleanup();
exit(0);
}
if (bind(ServerSocket, (struct sockaddr*)&ServerInfo,
sizeof(struct sockaddr)) == SOCKET_ERROR)
{
cout << "Bind fail." << endl;
closesocket(ServerSocket);
WSACleanup();
exit(0);
}
while (1)
{
FromClient_Size = sizeof(FromClient);
Recv_Size = recvfrom(ServerSocket, Buffer, BUFFER_SIZE, 0,
(struct sockaddr*)&FromClient, &FromClient_Size);
if (Recv_Size < 0)
{
cout << "recvfrom() error!" << endl;
exit(0);
}
cout << "Receive! client IP: " << inet_ntoa(FromClient.sin_addr) << endl;
cout << "Data: " << Buffer << endl;
}
closesocket(ServerSocket);
WSACleanup();
}
I'm trying to create a server client that once its working I can pass a vector into it and send it to a client program through ssh like putty. The issue is whenever I try to connect raw or ssh with putty on 127.0.0.1:45000 the program terminates once it connects.
Here is my code:
#include <iostream>
#include <WS2tcpip.h>
#include <string>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
void main()
{
// Initialize winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &wsData);
if (wsOk != 0)
{
cerr << "Can't Intitialze winsock! Quiting" << endl;
return;
}
// Create a socket to bind
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET)
{
cerr << "Can't create a socket! Quitting" << endl;
}
// Bind the socket to an ip address to the port
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(45000);
hint.sin_addr.S_un.S_addr = INADDR_ANY; // could also use inet_pton
bind(listening, (sockaddr*)&hint, sizeof(hint));
// Tell winsock the socket is for listening
listen(listening, SOMAXCONN);
// Wait for connection
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);
char host[NI_MAXHOST]; //Clients remote name
char service[NI_MAXHOST]; // Service (port) the client is on
ZeroMemory(host, NI_MAXHOST);
ZeroMemory(service, NI_MAXHOST); // use mem set of linux
if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
{
cout << host << " connected on port " << service << endl;
return;
}
else
{
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " connected on port " <<
ntohs(client.sin_port) << endl;
return;
}
// Close listening socket
closesocket(listening);
// while loop; accept and echo message back to client
char buf[4096];
while (true)
{
ZeroMemory(buf, 4096);
// wait for client to send data
int bytesReceived = recv(clientSocket, buf, 4096, 0);
if (bytesReceived == SOCKET_ERROR)
{
cerr << "Error in recv(). Quitting" << endl;
break;
}
if (bytesReceived == 0)
{
cout << "Client Disconnected, bytes 0" << endl;
break;
}
// echo message back to client
send(clientSocket, buf, bytesReceived + 1, 0);
// Close the socket
}
closesocket(clientSocket);
// Shutdown winsock
WSACleanup();
}
I'm writing it and compiling in Visual Studio 2019.
Here's the message I get from Putty when trying to connect with the ssh option or raw.
If anyone can help it would be greatly appreciated. Thanks!
When calling getnameinfo(), you are return'ing from main() immediately, without calling closesocket() first, regardless of whether getnameinfo() is successful or fails. This is the root of your Putty error. You are explicitly exiting your app whenever a client connects, without informing the client that the connection is being closed.
More generally, if accept() is successful (and socket(), too), you should always call closesocket() on the returned SOCKET, regardless of anything else happening in your code (same with WSACleanup() if WSAStartup() is successful).
There are several other mistakes in your code:
It is illegal for main() to have a non-int return type (though some compilers allow this, as a non-standard extension. Don't rely on this!).
You are missing a return from main() if socket() fails.
You are not checking for errors on bind(), listen(), accept(), or send().
There is no point in setting the backlog to SOMAXCONN if you are only going to accept() 1 client ever.
you have a potential buffer overflow when calling send(). Imagine if recv() returned exactly 4096 bytes received. Sending bytesReceived + 1 number of bytes back to the client would go out of bounds of your buf array.
With that said, try something more like this:
#include <iostream>
#include <WS2tcpip.h>
#include <string>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
int main()
{
// Initialize winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int errCode = WSAStartup(ver, &wsData);
if (errCode != 0)
{
cerr << "Can't initialize winsock! Error " << errCode << ". Quitting" << endl;
return 0;
}
// Create a socket to bind
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET)
{
errCode = WSAGetLastError();
cerr << "Can't create listening socket! Error " << errCode << ". Quitting" << endl;
WSACleanup();
return 0;
}
// Bind the socket to an ip address to the port
sockaddr_in hint = {};
hint.sin_family = AF_INET;
hint.sin_port = htons(45000);
hint.sin_addr.s_addr = INADDR_ANY; // could also use inet_pton
if (bind(listening, (sockaddr*)&hint, sizeof(hint)) == SOCKET_ERROR)
{
errCode = WSAGetLastError();
cerr << "Can't bind listening socket! Error " << errCode << ". Quitting" << endl;
closesocket(listening);
WSACleanup();
return 0;
}
// Tell winsock the socket is for listening
if (listen(listening, 1) == SOCKET_ERROR)
{
errCode = WSAGetLastError();
cerr << "Can't open listening socket! Error " << errCode << ". Quitting" << endl;
closesocket(listening);
WSACleanup();
return 0;
}
// Wait for connection
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);
if (clientSocket == INVALID_SOCKET)
{
errCode = WSAGetLastError();
cerr << "Can't accept a client! Error " << errCode << ". Quitting" << endl;
closesocket(listening);
WSACleanup();
return 0;
}
char host[NI_MAXHOST]; //Clients remote name
char service[NI_MAXHOST]; // Service (port) the client is on
ZeroMemory(host, NI_MAXHOST);
ZeroMemory(service, NI_MAXHOST); // use mem set of linux
if (getnameinfo((sockaddr*)&client, clientSize, host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
{
cout << host << " connected on port " << service << endl;
}
else
{
inet_ntop(AF_INET, &(client.sin_addr), host, NI_MAXHOST);
cout << host << " connected on port " << ntohs(client.sin_port) << endl;
}
// Close listening socket
closesocket(listening);
listening = INVALID_SOCKET;
// while loop; accept and echo message back to client
char buf[4096];
while (true)
{
// wait for client to send data
int bytesReceived = recv(clientSocket, buf, sizeof(buf), 0);
if (bytesReceived == SOCKET_ERROR)
{
errCode = WSAGetLastError();
cerr << "Error reading from client: " << errCode << ". Quitting" << endl;
break;
}
if (bytesReceived == 0)
{
cout << "Client Disconnected" << endl;
break;
}
// echo message back to client
char *ptr = buf;
int bytesToSend = bytesReceived;
do
{
int bytesSent = send(clientSocket, ptr, bytesToSend, 0);
if (bytesSent == SOCKET_ERROR)
break;
ptr += bytesSent;
bytesToSend -= bytesSent;
}
while (bytesToSend > 0);
if (bytesToSend != 0)
{
errCode = WSAGetLastError();
cerr << "Error writing to client: " << errCode << ". Quitting" << endl;
break;
}
}
// Close the client socket
closesocket(clientSocket);
// Shutdown winsock
WSACleanup();
return 0;
}
I've been trying for days to send a short, plain-text email to myself with C++. I'm using Visual Studio Express 2015. I'm eventually hoping to email automatic alerts to myself. I am using a Gmail account. I can't seem to manage to get this to work. I can send data, but can't receive. The server is closing my connection with Error 10054. (You can read about what that error means on this page.)
Here is the history: I have cobbled all this together from lots of S.O. posts and MSDN articles. I used to have a functional WSASetSocketSecurity section in this code, but for whatever reason, my connection attempts were timing out, so I omitted it. At this point, I will settle for the server not severing my connection when I send EHLO or HELO.
I'm really at a loss for how to proceed. Days of exploration, dozens of read articles, hundreds of dead ends. I hope that you'll forgive the few bits of junk code and that S.O. removed my hand alignments. Please take a look, let me know what I am doing wrong, let me know of any improper style, or anything else that offends your good-coder sensibilities. Many thanks.
#include "stdafx.h"
#include <exception>
#include <string>
#include <iostream> // In-out stream objects for development
#include <stdio.h> // Standard in-out for development
#include <winsock2.h> // For making socket connection to email server
#include <Mstcpip.h>
#include <Ws2tcpip.h> // Enhanced protocols to assist winsock2.h
#pragma comment(lib, "Ws2_32.lib") // Library for winsock2.h
#pragma comment(lib, "Fwpuclnt.lib") // Library for winsock2.h
#define BUFFER_SIZE 512
using namespace std;
void cleanup(SOCKET ConnectSocket, struct addrinfo *result) {
if (ConnectSocket != INVALID_SOCKET) {
closesocket(ConnectSocket);
}
freeaddrinfo(result);
WSACleanup();
cout << "socket closed" << endl;
cin.get(); // Development only
}
int _tmain(int argc, char* argv[]) {
// Initialize email parameters
char bccAddresses[64] = "";
char fromAddress[64] = "my_email#host.com";
char msg[512] = "Hello world!";
char port[12] = "465";
char serverName[64] = "smtp.host.com";
char toAddresses[64] = "my_email#host.com";
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL;
struct addrinfo *ptr = NULL;
struct addrinfo hints;
WSADATA wsaData;
try {
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult == SOCKET_ERROR) {
cout << "Error " << iResult << endl;
throw std::exception("WSAStartup failed\n");
}
cout << "WSAStartup successful: " << iResult << endl;
// Set up the hints socket address structure
ZeroMemory(&hints, sizeof(hints));
hints.ai_flags = AI_SECURE;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(serverName, port, &hints, &result);
if (iResult == SOCKET_ERROR) {
cout << "Error " << WSAGetLastError() << endl;
throw std::exception("getaddrinfo failed\n");
}
cout << "getaddrinfo successful: " << iResult << endl;
// Connect to the socket
ptr = result;
ConnectSocket = WSASocket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol, NULL, 0, 0);
if (ConnectSocket == INVALID_SOCKET) {
cout << "Error " << WSAGetLastError() << endl;
throw std::exception("Error at socket\n");
}
cout << "WSASocket successful: " << iResult << endl;
// Connect via the socket
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
cout << "Error " << WSAGetLastError() << endl;
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
throw std::exception("Unable to connect to server!\n");
}
cout << "connect successful: " << iResult << endl;
// Send message
char sendBuffer[BUFFER_SIZE] = "What is your malfunction";
char recvBuffer[BUFFER_SIZE];
sprintf_s(sendBuffer, BUFFER_SIZE, "EHLO %s%s", serverName, "\r\n");
iResult = send(ConnectSocket, sendBuffer, BUFFER_SIZE, 0);
if (iResult == SOCKET_ERROR) {
cout << "Error " << WSAGetLastError() << endl;
throw std::exception("WINSOCK send failed\n");
}
cout << "Sent:\n" << sendBuffer << "Byte count: " << iResult << endl;
iResult = recv(ConnectSocket, recvBuffer, BUFFER_SIZE, 0);
if (iResult == SOCKET_ERROR) {
cout << "Error " << WSAGetLastError() << endl;
throw std::exception("WINSOCK recv failed\n");
}
cout << "EHLO response: " << iResult << endl;
sprintf_s(sendBuffer, BUFFER_SIZE, "QUIT%s", "\r\n");
iResult = send(ConnectSocket, sendBuffer, BUFFER_SIZE, 0);
if (iResult == SOCKET_ERROR) {
cout << "Error " << WSAGetLastError() << endl;
throw std::exception("WINSOCK send failed\n");
}
cout << "Sent:\n" << sendBuffer << "Byte count: " << iResult << endl;
iResult = recv(ConnectSocket, recvBuffer, BUFFER_SIZE, 0);
if (iResult < 0) {
cout << "Error " << WSAGetLastError() << endl;
throw std::exception("WINSOCK recv failed\n");
}
cout << "Quit response: " << iResult << endl;
// Shutdown the connection
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
cout << "Error " << WSAGetLastError() << endl;
throw std::exception("shutdown failed\n");
}
// Clean up
cleanup(ConnectSocket, result);
return 0;
}
catch (std::exception err) {
printf(err.what());
cleanup(ConnectSocket, result);
return 1;
}
catch (...) {
printf("Unknown error\n");
cleanup(ConnectSocket, result);
return 2;
}
}
Three parts to this answer.
MIME Encode the username and password.
ACTUALLY send the username and password! :)
Some servers are skeptical and want you to say HELO or EHLO twice.
I will post full code soon. Although I feel I was about 40% of the way there, I owe my success to this site: http://www.coastrd.com/smtps.
I am using this code snippet from an internet website, and according to it, this code works fine. But I'm unable to connect to server. Code and error are given below:
This is the code:
#include <iostream>
#include <winsock2.h>
#include <string>
#include <conio.h>
int main()
{
WSAData version; //We need to check the version.
WORD mkword = MAKEWORD(2, 2);
int what = WSAStartup(mkword, &version);
if (what != 0){
std::cout << "This version is not supported! - \n" << WSAGetLastError() << std::endl;
}
else{
std::cout << "Good - Everything fine!\n" << std::endl;
}
SOCKET u_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (u_sock == INVALID_SOCKET)
std::cout << "Creating socket fail\n";
else
std::cout << "It was okay to create the socket\n";
//Socket address information
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("10.3.34.131");
addr.sin_port = htons(80);
/*==========Addressing finished==========*/
//Now we connect
int conn = connect(u_sock, (SOCKADDR*)&addr, sizeof(addr));
if (conn == SOCKET_ERROR){
std::cout << "Error - when connecting " << WSAGetLastError() << std::endl;
closesocket(u_sock);
WSACleanup();
}
//Send some message to remote host
char* mymsg = "success";
char vect[512] = { 0 };
int smsg = send(u_sock, mymsg, strlen(mymsg), 0);
if (smsg == SOCKET_ERROR){
std::cout << "Error: " << WSAGetLastError() << std::endl;
WSACleanup();
}
int get = recv(u_sock, vect, 512, 0);
if (get == SOCKET_ERROR){
std::cout << "Error in Receiving: " << WSAGetLastError() << std::endl;
}
std::cout << vect << std::endl;
closesocket(u_sock);
_getch();
return 0;
}
This is the error:
How can I correct this error?
Your network has no machine with IP address 10.3.34.131 that is listening on port 80. Or, if it does, that machine is rejecting your machine's connections to it.
i'm making a small IRC server, but I've come across a problem; upon trying to listen to the socket, i get error 10022 (Invalid Argument).
The error also appears on accept(), but this is because the socket isn't listening (the problem i'm posting about).
I didn't include the accept function because i feel it isn't necessary and would be adding pointless code.
#include <iostream>
#include <ws2tcpip.h>
#include <winsock2.h>
#include <thread>
#include <string>
#pragma comment(lib, "Ws2_32.lib")
#define maxConnections 10
class Server
{
struct sockaddr_storage their_addr;
struct addrinfo hints, *res;
struct addrinfo *servinfo;
int status;
SOCKET sock;
public:
void Start(const char *port);
};
void Server::Start(const char *port)
{
WSADATA WSAData;
if (WSAStartup(MAKEWORD(2, 0), &WSAData) != 0)
{
std::cout << "[ERROR]: " << GetLastError() << ".\n";
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
status = getaddrinfo(NULL, port, &hints, &res);
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock == SOCKET_ERROR)
{
std::cout << "[ERROR]: " << WSAGetLastError() << "Bad Socket.\n";
}
bind(sock, res->ai_addr, res->ai_addrlen);
Error:
if (listen(sock, maxConnections) == SOCKET_ERROR)
{
std::cout << "[ERROR]: " << WSAGetLastError() << " Listening Failed.\n";
}
The code above details the socket creation and binding, all of which are successful (though not necessarily right). The socket creation including 'NULL' might be the issue.
Thanks :)
WSAStartup() and getaddrinfo() do not use (WSA)GetLastError(), they directly return the actual error code instead. You are not accounting for that in your error messages.
socket() returns INVALID_SOCKET on failure, not SOCKET_ERROR.
When using getaddrinfo() to create a listening socket, you should specify AI_PASSIVE in the addrinfo.ai_flags field of the hints parameter. That will fill the output addrinfo with data that is suitable to pass to bind().
Try something more like this:
class Server
{
private:
bool winsockStarted;
SOCKET sock;
...
public:
Server();
~Server();
bool Start(const char *port);
void Stop();
...
};
Server::Server()
: sock(INVALID_SOCKET), winsockStarted(false)
{
WSADATA WSAData = {0};
int status = WSAStartup(MAKEWORD(2, 0), &WSAData);
if (status != 0)
std::cout << "[ERROR]: " << status << " Unable to start Winsock." << std::endl;
else
winsockStarted = true;
}
Server::~Server()
{
Stop();
if (winsockStarted)
WSACleanup();
}
bool Server::Start(const char *port)
{
Stop();
struct addrinfo hints = {0};
struct addrinfo *res = NULL;
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
int status = getaddrinfo(NULL, port, &hints, &res);
if (status != 0)
{
std::cout << "[ERROR]: " << status << " Unable to get address info for Port " << port << "." << std::endl;
return false;
}
SOCKET newsock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (newsock == INVALID_SOCKET)
{
std::cout << "[ERROR]: " << WSAGetLastError() << " Unable to create Socket." << std::endl;
freeaddrinfo(res);
return false;
}
if (bind(newsock, res->ai_addr, res->ai_addrlen) == SOCKET_ERROR)
{
std::cout << "[ERROR]: " << WSAGetLastError() << " Unable to bind Socket." << std::endl;
freeaddrinfo(res);
closesocket(newsock);
return false;
}
freeaddrinfo(res);
if (listen(newsock, maxConnections) == SOCKET_ERROR)
{
std::cout << "[ERROR]: " << WSAGetLastError() << " Unable to Listen on Port " << port << "." << std::endl;
closesocket(newsock);
return false;
}
sock = newsock;
return true;
}
void Server::Stop()
{
if (sock != INVALID_SOCKET)
{
closesocket(sock);
sock = INVALID_SOCKET;
}
}
I reread my code and realized that i need to add a check here
status = getaddrinfo(NULL, port, &hints, &res);
I changed it to
if (status = getaddrinfo(NULL, port, &hints, &res) != 0)
{
std::cout << "[ERROR]: " << WSAGetLastError() << "Get Address Info failed.\n";
}
and startup was successful.
If someone could explain why, i'll improve my answer.