Port for application listening - windows

I have an application that I'm currently testing that listens for requests over the network on port 1025. I chose this port arbitrarily and it is easy to change, my concern is that my application will collide with other system processes listening on that port. My two primary question are as follows:
Are there common system processes that use port 1025 that may conflict with my application?
Assuming the answer to 1) is yes, what is another less commonly used port or range of ports my application can safely utilize?

Any port in the 49152 – 65535 range cannot be registered by any company, and therefore you're more likely to not run into any problems with port conflicts.
A list of registered ports, etc. can be found at this wikipedia link here.
If you don't like Wikipedia, check this link out, from the Internet Assigned Numbers Authority (IANA).

That'll do in most cases. If you need to run more than one instance (a listener) of your application on the same IP address, for example, the port collision still occurs. To overcome this case, you may choose to bind your socket to port 0 (= any port) to have system assign the port number for you. Then you can use getsockname() (BSD socket API), or equivalents, to get the actual port number the system has assigned for the socket. Downside of it is obviously that the port number will change every time. There needs to be a way to tell (either manually, programmatically or systematically) its listening port to connectors. In fact, many VoIP/peer-to-peer applications work this way, with a help of 'rendezvous' server.

Related

NiFi: port to use in handlehttprequest

NiFi 1.5:
i want to use the port in HandleHTTPRequest. how to decide the port can be used in HandleHTTPRequest? is there any range of port can be used here.
i already saw the nifi configuration, but could not find the ports that can be used here.
please guide me. thanks.
Any port that the OS user running NiFi can access can be used for HandleHttpRequest, but only one can be used at a time (not a range). For example, sometimes the "NiFi user" (meaning the OS user that executed the nifi.sh command to start it) isn't allowed to use system ports (<1024) so you'd need to choose one above that number. Also you need to choose a port that is not already in use by another process.
The reason a port range is not available is because HandleHttpRequest is meant to model a well-known URL as a web service; if the ports could change, the clients would all have to try the same range.

Multiple clients - one server - one port? [duplicate]

This question already has answers here:
Does the port change when a server accepts a TCP connection?
(3 answers)
Closed 4 years ago.
I understand the basics of how ports work. However, what I don't get is how multiple clients can simultaneously connect to say port 80. I know each client has a unique (for their machine) port. Does the server reply back from an available port to the client, and simply state the reply came from 80? How does this work?
First off, a "port" is just a number. All a "connection to a port" really represents is a packet which has that number specified in its "destination port" header field.
Now, there are two answers to your question, one for stateful protocols and one for stateless protocols.
For a stateless protocol (ie UDP), there is no problem because "connections" don't exist - multiple people can send packets to the same port, and their packets will arrive in whatever sequence. Nobody is ever in the "connected" state.
For a stateful protocol (like TCP), a connection is identified by a 4-tuple consisting of source and destination ports and source and destination IP addresses. So, if two different machines connect to the same port on a third machine, there are two distinct connections because the source IPs differ. If the same machine (or two behind NAT or otherwise sharing the same IP address) connects twice to a single remote end, the connections are differentiated by source port (which is generally a random high-numbered port).
Simply, if I connect to the same web server twice from my client, the two connections will have different source ports from my perspective and destination ports from the web server's. So there is no ambiguity, even though both connections have the same source and destination IP addresses.
Ports are a way to multiplex IP addresses so that different applications can listen on the same IP address/protocol pair. Unless an application defines its own higher-level protocol, there is no way to multiplex a port. If two connections using the same protocol simultaneously have identical source and destination IPs and identical source and destination ports, they must be the same connection.
Important:
I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.
First remember below two rules:
Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL} not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT} - Protocol is an important part of a socket's definition.
OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.
Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP} and socket2{SRC-B, 100, DEST-X,80, TCP}. This means host A connects to server X's port 80 and another host B also connects to the same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single-threaded or multiple-threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.
To answer the original question of the post:
Irrespective of stateful or stateless protocols, two clients can connect to the same server port because for each client we can assign a different socket (as the client IP will definitely differ). The same client can also have two sockets connecting to the same server port - since such sockets differ by SRC-PORT. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.
To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to the same port, there could be more than one socket (maybe from the same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to the appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which the client initially tried to connect. If any server allocates different server ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.
A bit more for completeness:
Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of the parameters defining sockets then the answer is no. This is so because we can say that in such a case, a single client trying to connect to a server port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However, this is the WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in the same node can listen to the same port only if they are using different protocols. For example, two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server processes.
Server Types - single & multiple:
When a server processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server process. If a server uses only a single child process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called a multi-process/threaded server. Note that irrespective of the server's type a server can/should always use the same initial socket to respond back (no need to allocate another server port).
Suggested Books and the rest of the two volumes if you can.
A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')
Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by the parent-child relationship. OS's (especially UNIX) by design allows a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that process A listening to can be listened to by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to the same socket. In addition, also note that this rule of disallowing two independent processes to listen to the same socket lies on an OS (or its network libraries), and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restriction.
TCP / HTTP Listening On Ports: How Can Many Users Share the Same Port
So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.
Intuitively (and wrongly), most people assume that it looks something like this:
Local Computer | Remote Computer
--------------------------------
<local_ip>:80 | <foreign_ip>:80
^^ not actually what happens, but this is the conceptual model a lot of people have in mind.
This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.
Three things must be understood:
1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.
2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.
3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.
So, this is really what gets created when a client connects to a server:
Local Computer | Remote Computer | Role
-----------------------------------------------------------
0.0.0.0:80 | <none> | LISTENING
127.0.0.1:80 | 10.1.2.3:<random_port> | ESTABLISHED
Looking at What Actually Happens
First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).
netstat -atnp | grep -i ":500 "
As expected, the output is blank. Now let's start a web server:
sudo python3 -m http.server 500
Now, here is the output of running netstat again:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all". An easy mistake to make is to listen on address 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.
So now, let's connect a user to our machine:
quicknet -m tcp -t localhost:500 -p Test payload.
This is a simple script (https://github.com/grokit/dcore/tree/master/apps/quicknet) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
tcp 0 0 192.168.1.10:500 192.168.1.13:54240 ESTABLISHED -
If you connect with another client and do netstat again, you will see the following:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
tcp 0 0 192.168.1.10:500 192.168.1.13:26813 ESTABLISHED -
... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.
Normally, for every connecting client the server forks a child process that communicates with the client (TCP). The parent server hands off to the child process an established socket that communicates back to the client.
When you send the data to a socket from your child server, the TCP stack in the OS creates a packet going back to the client and sets the "from port" to 80.
Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.
When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.
Words in italics are system calls.
Ref
http://www.scs.stanford.edu/07wi-cs244b/refs/net2.pdf

On the linux network socket server machine, what happens when all network ports are allocated for clients

On the linux network socket server machine, what happens when all network ports are allocated for clients? If it happens, the connection request from clients are denied, or delayed? If that's right, is it right to think that one linux machine can serve at most the number of open ports simultaneously? (under assumption that all other resources are enough)
If that's right, is it right to think that one linux machine can serve at most the number of open ports simultaneously?
No, the port is not the limiting factor here. TCP connected socket is actually a quintuple (src_port, src_address, dest_port, dest_address, protocol).
So, for every server listening on one port, every client will be able to make whatever is set in ip_local_port_range connections using the same protocol.
However, you can work around this - if you have more IP addresses (you could use IP aliasing for this, even if you don't have more than one interface), or if your server is listening on more than one port, the number of possible connections goes up.
Resources:
http://vincent.bernat.im/en/blog/2014-tcp-time-wait-state-linux.html

Generate port number at runtime in Linux [duplicate]

I need to create a program that will communicate with other programs on the same computer via UDP sockets. It will read commands from stdin, and some of this commands will make it to send/receive packets without halting execution. I've read some information out there, but since I'm not familiar with socket programming and need to get this done quickly, I have the following questions:
I need to get a random unused port for the program to listen to, and reserve it so other programs can communicate with this and also the port isn't reserved by another program. I also need to store the port number on a variable for future usage.
Since the communication is across processes on the same machine, I'm wondering if I can use PF_LOCAL.
Also a code sample of the setup of such socket would be welcome, as well as an example of sending/receiving character strings.
Call bind() specifying port 0. That will allow the OS to pick an unused port. You can then use getsockname() to retreive the chosen port.
Answer by Remy Lebeau is good if you need a temporary port. It is not so good if you need a persistent reserved port because other software also uses the same method to get a port (including OS TCP stack that needs a new temporary port for each connection).
So the following might happen:
You call bind with 0 and getsockname() to get a port;
then save it into config (or into several configs) for future uses;
software that needs this port starts and binds the port.
Then you need to e.g. restart the software:
software stops and unbinds the port: the port can now be returned by bind(0) and getsockname() again;
e.g. TCP stack needs a port and binds your port;
software can't start because port is already bound.
So for "future uses" you need a port that is not in ephemeral port range (that's the range from which bind(host, 0) returns a port).
My solution for this issue is the port-for command-line utility.
If it being a random port is actually important, you should do something like:
srand(time(NULL));
rand() % NUM_PORTS; // NUM_PORTS isn't a system #define
Then specify that port in bind. If it fails, pick a new one (no need to re-seed the random generator. If the random port isn't important, look at Remy Lebeau's answer.

Is there a Windows socket API call / option to "block" a range of ports à la SO_EXCLUSIVEADDRUSE

In this (rather old) article, the author states:
"Port Blocking
Port blocking allows an application to prevent other applications from performing specific binds to the ports within a specified range. When blocking a port range, the application must choose a contiguous range of port numbers that are between the value of the MaxUserPort setting (5000 by default) + 1 and either 49151 (for Windows XP and Windows Server 2003 with no service packs installed) or 65535 (for Windows Server 2003 Service Pack 1). There should be no existing bindings to the ports within the range of blocked ports. Windows Sockets returns the last port number in the blocked range as the handle. When unblocking (removing the block), Windows Sockets unblocks the range that has the same left edge as the unblock request."
The implication I get from reading this is that there is some api an application can use to set/unset this, but I have drawn complete blanks trying to search documentation for any such thing, nor do I recall ever seeing such functionality in my socket programming days.
Is there such a capability in Windows, and if so, pointers to documentation of it will be heartily appreciated!
There is no such call in the winsock API itself, but I believe there is in the LSP feature. Another (easy but dirty <3) way is to just bind() to all the ports you want blocked.
You can set the range of ports which will be used for dynamic clients (binding to any available socket) on the system by the MaxUserPort registry value (applicable from Vista onwards). The dynamic port range can be set for tcp and udp sockets. More details in the following links :
MaxUserPort
KB929851
So you can set the range (to allow), as per your needs

Resources