Sasha Tim
Sasha Tim

Reputation: 1

I have an issue creating a server socket on c++ for listening the connections via internet

I tried to make a server socket for connecting client sockets via internet. I found nothing in google.

Unfortunately, it works only with my local network. It responds when I connect to 127.0.0.1 through a browser on the same PC, but doesn't accept connections from other PCs outside of the local network.

Here is my code for creating the server socket. I get the address with getaddrinfo() and bind() the socket. The code is working, but only within my local network. When I try to connect to this socket from another PC, I get nothing.

WSADATA wsaData;

int result = WSAStartup(MAKEWORD(2, 2), &wsaData);

if (result != 0)
{
    cerr << "WSAStartup failed: " << result << "\n";
    return result;
}

struct addrinfo* addr = NULL;
ZeroMemory(&addr, sizeof(addr));

struct addrinfo hints;
ZeroMemory(&hints, sizeof(hints));

hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
    
result = getaddrinfo(NULL, "5000", &hints, &addr);

if (result != 0)
{
    cerr << "getaddrinfo failed: " << result << "\n";
    WSACleanup();
    return 1;
}

//Creating socket

int listen_socket = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);

if (listen_socket == INVALID_SOCKET)
{
    cerr << "Error at socket: " << WSAGetLastError() << "\n";
    freeaddrinfo(addr);
    WSACleanup();
    return 1;
}

result = bind(listen_socket, addr->ai_addr, addr->ai_addrlen);

if (result == SOCKET_ERROR)
{
    cerr << "bind failed with error: " << WSAGetLastError() << "\n";
    freeaddrinfo(addr);
    closesocket(listen_socket);
    WSACleanup();
    return 1;
}

//listening
if (listen(listen_socket, SOMAXCONN) == SOCKET_ERROR)
{
    cerr << "listen failed with error: " << WSAGetLastError() << "\n";
    closesocket(listen_socket);
    WSACleanup();
    return 1;
}

Upvotes: 0

Views: 60

Answers (0)

Related Questions