user900785
user900785

Reputation: 423

TCP/IP basics: Destination port relevance

Ok this is kind of embarassing but I just have a rather "noob" question.

In a client server TCP communications, where my system is a client accessing a remote server at say Port XX, isnt the client opening a random port YY in its system to talk to remote port XX? So when we code we do specify the destination port XX right?

For the client, the port YY itself is chosen when the socket is created, isnt it?

Is there anyway I could monitor/restrict/control any client talking to a particular server?(like say clients talking to servers at specific serving ports??)

Is there any IPTABLE rule or some firewall rule restricting the client? Can this be done at all??

Are destination ports saved in the socket structures? If so where??

Thanks!

Upvotes: 3

Views: 895

Answers (2)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

First, server side creates a listening socket, with the chain of socket(2), bind(2), and listen(2) calls, then waits for incoming client connection requests with the accept(2) call. Once a client connects (socket(2) and then connect(2) on the client side) and the TCP/IP stacks of the client and the server machines complete the three way handshake, the accept(2) returns new socket descriptor - that's the server's end of the connected socket. Both bind(2) on the server side, and connect(2) on the client side take server's address and port.

Now, the full TCP connection is described by four numbers - server address, server port, client address, and client port. The first two must obviously be known to the client prior to the connection attempt (otherwise, where do we go?). The client address and port, while could be specified explicitly with the bind(2), are usually assigned dynamically - the address is the IP address of the outgoing network interface, as determined by the routing table, and the port selected out of range of ephemeral ports.

The netstat(8) command shows you established connections. Adding -a flag lets you see listening sockets, -n flag disables DNS and service resolution, so you just see numeric addresses and ports.

Linux iptables(8) allows you to restrict where clients are allowed to connect to. You can restrict based on source and destination ports, addresses, and more.

You can get socket local binding with getsockname(2) call, remote binding is given by getpeername(2).

Hope this makes it a bit more clear.

Upvotes: 5

JJ.
JJ.

Reputation: 5475

Yes you can create a firewall rule to prevent outbound TCP connections to port XX. For example, some organizations prevent outbound TCP port 25, to prevent spam being sent from network PCs to remote SMTP servers.

Upvotes: 1

Related Questions