I'm trying a write something like a small proxy on SDL & SDL_Net.
My program successfully creates a server and waits for incoming connection. But for some reason it ignores entered port and always uses 24862. If I start another instance, it picks another random free port.
This is my code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <csignal>
#include <string>
#include "SDL2/SDL.h"
#include "SDL2/SDL_net.h"
void Error(const char *txt)
{
std::cout << txt;
static volatile int v = 0;
while (1)
v++;
}
int main(int, char **)
{
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_NOPARACHUTE))
Error("SDL init failed!");
if (SDLNet_Init())
Error("SDL net plugin init failed!");
TCPsocket srv1, srv2, con;
IPaddress con_ip, host_ip;
{
{
auto handler = [](int){std::exit(0);};
std::signal(SIGFPE, handler);
std::signal(SIGILL, handler);
std::signal(SIGINT, handler);
std::signal(SIGBREAK, handler);
std::signal(SIGSEGV, handler);
std::signal(SIGTERM, handler);
std::signal(SIGABRT, handler);
}
std::cout << " < Wellcome to Retranslator! >\n\nWhat is your hosting port?\n>: ";
int hport = 0, cport = 0;
char c;
while (c = std::getchar(), c != '\n')
hport = hport * 10 + (c - '0');
std::cout << "[" << hport << "]\n";
std::cout << "What ip you want to connect to?\n>: ";
std::string ips;
while (c = std::getchar(), c != '\n')
ips += c;
std::cout << "[" << ips << "]\n";
std::cout << "What port you want to connect to?\n>: ";
while (c = std::getchar(), c != '\n')
cport = cport * 10 + (c - '0');
std::cout << "[" << cport << "]\n";
host_ip.host = INADDR_ANY;
host_ip.port = hport;
SDLNet_ResolveHost(&con_ip, ips.c_str(), cport);
if (con_ip.host == INADDR_NONE)
Error("IP parsing failed!");
srv1 = SDLNet_TCP_Open(&host_ip);
if (srv1 == 0)
Error("Server creation failed!");
std::cout << "Server created on port " << hport << "!\nWaiting for incoming connection...\n";
while (1)
{
srv2 = SDLNet_TCP_Accept(srv1);
if (srv2)
break;
}
std::cout << "Remote client joined!\n";
con = SDLNet_TCP_Open(&con_ip);
if (con == 0)
Error("Can't connect to application!");
std::cout << "Successfully connected to application!\n";
}
return 0;
}
I was surprised, because I already wrote a game which used SDL_Net. I checked port of that game's server with TCPview - it is 24862 too (it's supposed to be 7777)! Furthermore, the game's client successfully connects to it (and it also should connect to 7777)!
Also, that game's server complains about occupied port when I try to start two instances on 7777, but my new program does not.
I figured out what was wrong.
It's strange, but looks like port (uint16_t) needs to be represented in reversed byte order. So, 7777 becomed 24862.
(Also, my assumption about program picking a random free port was wrong, because i used 7777 for first instance and 7779 for second one.)