Issue
I want to build a program that will run on my Raspberry Pi and starts processes when I connect to it. I want to run a specific processes if there is a connection on a specific port.
So I need to get the port somebody is trying to connect to.
For example:
If I open localhost:4444
in my browser I want to get 4444 as a string or an int.
It doesn’t need to be C#. Would be great, but it can also be in other languages.
Is this possible and how can I achieve that?
Solution
Listening for an incoming packet on any port number, rather than on a specific port number, is an unnatural act on Linux (the rPi's OS) and on most operating systems.
You could probably, with a lot of work, figure out how to do it with the tcpdump command line utility and/or its underlying libpcap runtime library. This subsystem intercepts network messages at the driver level and reports them. You could write a hunk of code that notices an incoming connection request and launches a server (written in your language of choice) to listen on that port.
But, the server would not be launched in time to handle the request detected by tcpdump or libpcap. Instead, the OS on the rPi would reject it immediately with the ECONNREFUSED OS error. You would have to rely on the client software retrying the connection after the rPi had a chance to launch the server. But client software like web browsers don't automatically retry those refused connections.
You might be able to make this work, but it will always be a brittle solution and a miserable hack. You will be better off rethinking this system design. You should run servers (listeners) on any ports you think your clients will use.
I must mention the security hazards of the approach you propose. A cybercreep could crash your machine simply by running nmap on it if you started servers upon receiving messages on random ports.
Answered By - O. Jones Answer Checked By - Timothy Miller (WPSolving Admin)