Search code examples
socketsserverclientport

How to assign client port in socket?


I am new to socket programming. So currently I'm doing client-server connection in my computer. So the IP address for both client-server is 127.0.0.1. My question is, can I assign a specific client port to bind with the server? Instead of the OS chose the port number for me, can I assign it by myself? and if yes, can you help me on how to do this?

Thank you so much for your help.


Solution

  • You can make a client use a specific source address with bind, i.e. the same as you do for binding the server side address. But in most cases this additional effort is not worth it and might even result in troubles you did not had when using a system assigned port. Thus, don't do it unless it does not work without.