C++ Socket Programming- Finding client machines IP, TrueIP, and bind port - c++

I am having some trouble figuring out how to fill out a custom UDP header. The client normally connects to a server/port specified in the arguments, and optionally it also accepts a relay IP and port number, the relay then uses the info in the header to forward to the server. Currently the program works if provided a raw IP address (i.e. 127.0.0.1), however I cannot get the relay to function properly.
I am using the following arguments:
clientport=atoi(argv[5]); //port on current machine to bind (default 0)
relayport=atoi(argv[4]); //port on relay to connect to
relay = argv[3]; //relay IP
port = atoi(argv[2]); //server port
servername = argv[1]; //server IP
I need to fill out the following in my header for the relay (in network byte order):
uint32_t from_IP, to_IP; // Ultimate destination, not the relay
uint32_t trueFromIP, trueToIP; // AWS may change public IP vs private IP
uint16_t from_Port, to_Port; // Ultimate source & destination, Not relay
I understand that if 0 is provided for the clientport it will choose any port (this happens by default when binding), how can I figure out which port is chosen and include it as 'from_port'?
How do I get the client machine's IP address, and "true" IP address?
How can I detect if a hostname is used as an argument rather than an IP address, and how would I code it so either would work? Right now I am using something like :
inet_aton(servername OR relay, &server.sin_addr);
to fill out the sin_addr for the server/relay's sockaddr_in, which only works if provided an IP address.

after you call bind(), you can use getsockname() to find out the port that bind() chose.
a machine can have multiple IPs install, so to get the "true" IP, you need to know which specific NIC/Adapter is being used to communicate with the relay, and then you can retrieve that NIC/Adapter's IP. There is nothing in the socket API for getting that IP, you need to use platform-specific APIs instead, like GetAdaptersInfo()/GetAdapterAddresses() on Windows, or getifaddrs() on other platforms. Once you have decided on a particular NIC/adapter, you can bind() the client socket to that IP.
use getaddrinfo(), or just parse the string yourself using platform-specific APIs, like WSAStringToAddress() or RtlIpv(4/6)StringToAddress() on Windows.

Related

C++ / Qt: How can I detect when a hostname or IP address refers to the current system?

I'm writing a macOS C++ application using Qt that acts as both a UDP client and UDP server. The server functionality allows the user to configure which port the UDP packets will be received on, and the client functionality allows specifying both a target host and a port number. The host can be either a hostname or an IP address, including addresses or hostnames that resolve to a multicast or broadcast address.
In order to help prevent circularity, when the server functionality is enabled I need to be able to warn the user when the host and port they've entered for the client would send the packets directly to the app's server. Of course it's easy to check if the port numbers match, but this means I need to know whether the host they've entered refers to the current system.
Examples of hostnames or IP addresses that would typically be problematic:
127.0.0.1
localhost
192.168.1.255 (assuming the system is on a 192.168.1.0/24 subnet)
any of the IP addresses assigned to the current system's network interfaces
the system's local DNS name
any other loopback addresses that may be configured other than 127.0.0.1
How could I go about detecting this?
Since this app is being written using Qt, a solution that exclusively uses Qt's framework would be ideal. But if that's not possible (since Qt doesn't handle every possible use case) a macOS-specific solution will work too.
QNetworkInterface class should provide the most information you may need.
You can obtain a list of IP addresses using QNetworkInterface::allAddresses() static function.
You can also get a list of all interfaces using QNetworkInterface::allInterfaces().
Calling QNetworkInterface::addressEntries() for each QNetworkInterface returned by QNetworkInterface::allInterfaces() will give you more information about address entries for each interface.
auto ifs = QNetworkInterface::allInterfaces();
foreach (auto interface , ifs){
auto addresses = interface.addressEntries();
foreach ( auto addy , addresses){
///play with the addy here.
}
}
You can also test hostnames against those ip addresses which you are going to ban, using QDnsLookup class.

Remote address of active UDP connections in Windows using IP Helper

The function GetUdpTable() in IP Helper returns a table of MIB_UDPROW.
MIB_UDPROW struct does not contain any information about the remote address of the UDP connection, the extended variants of GetUdpTable() only adds the pid to the return struct.
Is it possible to get the remote address for an active UDP connection using IP Helper (or any other winapi)?
No, it is not possible to get the remote port of the UDP connection unless you capture traffic and inspect the packets since UDP is a connectionless protocol.
See: Get Destination Ip/Port of active udp Connection?

How to make a .cpp file to act as an accessible server

I have written a simple program with Linux (Cent OS 7.0) and C++. It is a very small server which sends back a string of characters to the client. But my problem is that I don't know how should I access that server using an IP address?
I have used Linux Socket Interface (Berkeley), and in the section which defines the address, my code does the following:
serverObject.
sin_family = AF_INET;
serverObject.sin_addr.
s_addr = htonl(INADDR_ANY);
serverObject.
sin_port = htonl(portNumber);
I use INADDR_ANY as my server's address which is defined in its definition as:
/* Address to accept any incoming messages. */
Now, how should I run the server, and then use my simple client program to send request to it. My simple client program accepts an IP address as it's destination address, this address should be the one destined toward to the server. How should I relate it then?
INADDR_ANY goes to specify that all active network interfaces in the system should be bound to. So if you're connected to more than one network, you'll be able to communicate with connections coming in from all of them. Most systems will usually have just one, though, and this still goes to say that if the IP bound to that interface happens to change, you'll still bind to that interface.
So, once you specify INADDR_ANY, you need to initiate connections according to the following rules:
If you're connecting from the same physical machine, the easiest thing would be to use the loopback interface (127.0.0.1). However, you can still do (2).
If you're connecting from another machine, you need to pick the accessible IP address of your server from that machine. As said above, if your server is only connected to one network, this will simply be the IP address of the server. Within an internal network this will often be something like 192.168.x.y, or 10.0.x.y—but it doesn't have to.
If you're connecting from a different network which uses a gateway to access your server, then you will need to set up port forwarding in the relevant routers so that when they receive connection to port X, they will know to internally transfer it to your server.
As a server programmer, you decide the port on which to listen, but not the address.
The internet address is provided by your internet provider, or 127.0.0.1 to test on your own machine.
There are plenty of web pages on internet that provide tools to tell you your current public address (search for What is my Ip).
Most of the "home" internet routers implement NAT: they have a single internet address and map them to many device, that carry the Port number to be changed (your port 80 become port (e.g.) 2345 for outside). To allows a client from outside your home to access your server, you are required to configure your router to map the server port, so for example your public port 80 map to your server port 80.
With that said, you should be able to connect your client to your server through an address and port.
If then you want to use a name (example.org) instead of an IP (93.184.216.34), a Domain Name Server is used. But that is another topic.

Manage 2 Internet Connections?

I have a Linux computer with 2 Ethernet adapters. I also have 2 ADSL models and 2 internet connections. I connect modem A to Ethernet port A and modem B to Ethernet port B.
Now, how to do the following (preferably in C++):
a) Get the IP of each adapter
b) Select the connection to use for downloading (I want to say: download this file with connection A and this with B)
The IPs are dynamic. I am doing this, because my IP must be know to a remote server.
The server must:
a) get the IP
b) send files to this IP
The idea is, every time my IP changes, I will send the new IP to the server, so the server will know where to send the files.
I am using 2 internet connections for:
a) redundancy reasons (if one internet connection is down, I got the second)
b) have faster download speed by opening 2 connections with the server.
If your goal is to simply update a server of your IP address, then you just need to make a connection to this server using a typical TCP socket:
int sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addrLocal = {};
result = connect(sock, (sockaddr*)&server_address, sizeof(server_address));
send(sock, "I have a new IP address", ...);
In the above example, you don't even have to call bind on the socket, as the client TCP/IP stack will consult your computer's routing table for the best local IP address to use (and will pick a random local port).
The client need not even know the IP address it is connecting from nor does it need to tell the server via the socket protocol.. The server in turn can automatically detect your IP address when it does the corresponding accept call when it receives the client connection.
sockaddr_in addrRemote = {};
socklen_t addrRemoteSize = sizeof(addrRemote);
int sockclient = accept(listensocket, (sockaddr*)&addrRemote, &addrRemoteSize);
// the IP address of the client making the connection is in addrRemote.
And if your client just keeps the socket to the server open, then the server can transmit a file back to the client without having to establish a new connection or keep track of any IP address.
Now to answer your original questions, in case you do have a legitimate need to do ascertain a local IP address.
Question 1:
To get the local IP address of each adapter, you can call getifaddrs . From the result list returned from this function, filter out any address that isn't IP, is not UP, or is LOOPBACK.
Question 2:
To bind a socket to a specific adapter, bind to the IP address of the local adapter prior to making a connect call. Example below
...
result = bind(sock, (sockaddr*)&addr, sizeof(addr));
if (result != -1)
connect(sock, (sockaddr_in*)&remoteServer, sizeof(remoteServer));
Where "addr" in the code sample above points to one of the ifa_addr values in the ifaddr array returned by getifaddrs.
Now if there is a NAT involved in any of these connections, then your locally enumerated IP address will be different than the public IP address that the server sees you at.
If you are using UDP sockets, then all of the stuff above still applies, with some tweaks. (e.g. don't call connect(), just call sendto() ).

C++ Sockets with Router

I'm making a multiplayer game using sockets and I have some problems with the server side.The server shall be run from my computer which is behind a router. Therefore I'm a little bit stuck with what should the server inet_addr be. I am using port 1234 and I forwarded it to my PC ( the place where I keep the server ).
I have tried using my own ip address which i got from myipaddress.com, also my computer's router address ( 192.168.0.101 ). The first try i was getting A LOT of connections which ended up in killing the program and in the second try nothing connects to it.
addr.sin_addr.s_addr= inet_addr("192.168.0.101");
addr.sin_port = htons(1234);
addr.sin_family = AF_INET;
What should I do in order to make any client be able to connect to the server and the server to run from behind the router ?
With port forwarding in your router, the router needs to know which device to send packets directed at the selected port range to. The router is asking for your internal IP address, (websites only see your external IP address).
You can find this on Windows by calling ipconfig in cmd (I believe the command may be ifconfig -a on Linux), this lists all of your network interfaces and your internal IP address on any that are connected. You should look for a value in the form 192.168.0.xxx.
When someone then wants to connect to your server if you give them your external IP address and desired port, their packet will be sent to your router on that port, and it will forward it to your computer at the internal IP address.
If you disconnect your computer from the network regularly you may need to configure your internal IP so that it is static and always allocated the same address.
This has nothing to do with your program, and everything to do with your network configuration. Go learn about NAT (network address translation) and doing port forwarding or DMZ on your router.
Usually you want your program to bind to all interfaces - INADDR_ANY - but the important one is the address on the network controlled by your router (often 192.168.0.0/16, but it can be any RFC1918 address block).
Once you have your network configured on your router and binding the external interface from your program (don't hard code an address like in your example, just use INADDR_ANY)
serv_addr.sin_addr.s_addr = inet_addr(INADDR_ANY);