When you connect with the host , you can just connect with the single port only.Because each port is for a single connection .So you can not get all the port with the single connection.If you want to get the available ports you need to have multiple connection.so each connection will try to occupy the port which is available.There while you can get the available ports on the host ( This is what your second program doing and getting the ports correctly ).

Then you asked to store the ip in the char[].Since you want this as a string I said 16 bits is enough.But if you want to store that as a integer you need 32 bits. Infact to do some operaton with the ip address you need to store that as a integer only.