Help me understand ports and port forwarding please

I have a few questions below on ports.

From my understanding ports are what allow information to come into your computer and each port interprets/allows specific information/data to come in. Is this correct from a ball park perspective? If not could some elaborate on this please.

What commands from terminal can I run to scan for open and closed ports on my mac?

My friend and I tried doing a remote log in to each others mac books using ssh and received a port 22 error. I've heard that you can reroute or forward this port 22. What is my computer actually telling incoming information to do when it forwards a port?

Last question, opening up these ports (port 22 for example), I would think would create a security risk. Therefore, how much at risk are the two computers with an open port 22 and how on earth can ssh be secure if it requires an open port.

I apologize for having so many questions however understanding IP addresses and using the ssh command really requires some basic knowledge on how ports work.

Ports are fields in UDP and TCP packet headers that allow the flow to be divided on a host to 65K different apps. For instance tcp cpnnections could be made from 63K different apps on one host to port 80 web server on the next. Sometimes port numbers imply a protocol, like 80 for http, 25 for smtp, etc. Servers listen on ports and clients get random ports to identify their socket from al others on the host, In IPV4, you have 2^32 hosts and 2^16 ports, so there are 2^96 possible connections. UDP is connectionless, so a "connection" is just a filter on remote host+port and default remote host+port destination on a socket.

IP packets are identified by Host and protocol (such as TCP), and for tcp and udp, by port. Firewalls like iptables key off the host and port. With tcp, you can tell which end is the client (connecting) and which is the server (listening) in the first two packets (syn and syn+ack bits on, respectively). So, you can allow clients inside to connect everywhere outside but not vice-versa. ICMP is an IP sub-protocol that supports IP, TCP, UDP with control and diagnostic messages Some ICMP messages can be toxic if counterfeit.

IPTables also has NAT, the ability to rewrite packets for a new host, port or both going "out", and back to the original host/port for packets coming "in". This is handy if inside hosts are unroutable, like 10.*, or just to hide inside hosts. Some protocols like FTP (which runs on top of, or inside, TCP) put hosts and port numbers in the data stream as well, and some of these NAT knows how to rewrite. All packet rewriting include adjustment of checksums.

1 Like