This is a basic question. I conclude the socket API semantic as below.
bind() - where I am connect() - where I want to send message
If I want to make a restriction that Tom and Jerry must talk through the following fixed connection:
Tom's IP:Tom's Po开发者_StackOverflow社区rt <--> Jerry's IP:Jerry's Port
I must call bind() on both sides to set their respective socket. Right?
And in the following code, I didn't explicitly bind() to the new_socket,
new_socket = accept(listen_socket, (struct sockaddr*)&remote_addr, &addr_size);
send_data(new_socket);
recv_data(new_socket);
But when I send and recv data throught the new_socket, it still uses the IP address and port number I bind() to the listen socket. Is that info implicitly copied to the new_socket by the system?
If the new_socket and the listen_socket both are bind to the same IP address and Port, how could the system tell them apart?
Thanks!
If the new_socket and the listen_socket both are bind to the same IP address and Port, how could the system tell them apart?
TCP protocol uses a tuple of { host-ip, host-port, peer-ip, peer-port } to identify connections. That is, you can have many incoming connections with the same { host-ip, host-port }-part (same as your listening socket), but with different { peer-ip, peer-port }-part. When you connect all your outgoing connections on the same ip have a different port.
精彩评论