1

I am confused about ports.

I find it odd that we need to bind different servers to different ports.

Example: Apache binded on 8080, Express.js can't bind on 8080

How does server port binding differ from application port listening?

Example: Different browsers, ie, chrome, firefox, can listening and communicated on port 80?

This issue came up when trying to run "grunt test:unit". There was a tomcat server that was already bound to 8080, but the server grunt starts, middleware I believe, is able to startup, but it is not able to to capture the browser. Stopping the tomcat server made things work.

TOBlender
  • 1,053
  • 11
  • 17

2 Answers2

4

Actually, Firefox, Chrome, etc. use different source ports. They don't listen on ports; they connect to remote servers. The servers are listening on one port (80). The source port from which the browser connects is chosen randomly and is a high number. You can check this using netstat. Their destination port is the same (80).

The reason why you can't have multiple servers binding to the same port* is because the operating system wouldn't know which application to hand off an incoming connection to.

*actually, you can, but it's complicated. SO_REUSEPORT

Community
  • 1
  • 1
Hut8
  • 6,080
  • 4
  • 42
  • 59
  • Thanks for the answer, I didn't know about the ports being random and different on the client. Also makes sense that it's possible to bind to the same port, it's just not done often as the extra complexity isn't really worth it. – TOBlender Aug 26 '13 at 21:55
1

The reason only one application can control/listen on a port at one time is this: When the OS receives a request for, say, port 80, and there were two apps listening on it, how is it supposed to know which app to pass on the request to?

The reason multiple apps can access the web at once is because they don't do it the same way - they use an unused port (maybe something like 62332 or whatever) and only the destination is port 80, for example.

That's what ports are for - so that you can run more than one server at once per machine.

Matt Randell
  • 374
  • 1
  • 3
  • 11