Android Question How to determine whether a port is idle?

watesoft

Active Member
Licensed User
Longtime User
I am using the httpserver lib. What method can I use to determine whether the set port is occupied and automatically allocate an unoccupied port?
 

drgottjr

Expert
Licensed User
Longtime User
you get an "Address already in use" exception if you try to bind to an already bound listening port. so you can wrap your start in a try/catch block and move gracefully to another port. since this is running on an android device, one wonders how many servers you're running at the same time.
 
Upvote 0

watesoft

Active Member
Licensed User
Longtime User
Thank you. When I set a port, the app always crashes when it starts, and then I changed the port. it's ok! so I think this port is probably occupied.
 
Upvote 0

drgottjr

Expert
Licensed User
Longtime User
so, use try/catch when you set the port. the "crash" should be captured by catch. log
lastexception to see what the error was. if it's "already occupied", you move to another port.

which ports are you using anyway? you shouldn't be crashing. http servers normally use
standard ports (80, 8080). if you're using a restricted port (eg, 25), you may be getting a
different error. ports below 1024 are normally reserved for use by root or services running as
root. port 80 is normally reserved for http (443 for https).

you need to find out what the exception is. it should either be in the log or you can trap it
with try/catch and log(lastexception)
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…