Android port number use

Will an android application be assigned a port number by default when it starts?

Won't. In Android, applications are usually not assigned a default port number. If an application needs to listen for network connections, it must explicitly specify the port number to use.

How to specify the port number? What are the classifications of port numbers?

In Android, the port number can be specified in code by using a socket. For example:

java
int port = 1234;
ServerSocket serverSocket = new ServerSocket(port);

Regarding the port number, it can generally be divided into the following categories:
System port: 0~1023, used to run standard services, such as HTTP service (port 80), FTP service (port 21), etc.
Registered ports: 1024~49151, used to run registered applications or services, such as DNS service (port 53), SMTP service (port 25), etc.
Dynamic/private ports: 49152~65535, can be dynamically assigned to any application or service, usually used for clients.
In general, dynamic/private ports are recommended. However, if you need to provide a specific service, you need to use the registration port.

How to ensure that the port number you specify is not occupied?

Before specifying the port number, you need to make sure that the port is not occupied by other programs. This can be achieved by
trying to open the port before starting the service, if that fails the port is already in use.
Use the isBound() and isClosed() methods to ensure whether the port is occupied or closed.

scss
ServerSocket serverSocket = new ServerSocket(port);
if (serverSocket.isBound() && !serverSocket.isClosed()) {
    
    
  // Port is available
} else {
    
    
  // Port is not available
}

NOTE: If this port is already in use, you should choose a different port or wait until it becomes available.

Guess you like

Origin blog.csdn.net/u013168615/article/details/128833807