Ramana Reddy
Ramana Reddy

Reputation: 399

How to know whether a port is open/close in socket programming?

If a socket program runs on a port(say 6053) and if the rule is not added in the firewall the functions recv read and recvfrom are blocked.

How do we check this in C or python and report Port not opened error on linux machines.

Upvotes: 4

Views: 1774

Answers (2)

Karthik Balaguru
Karthik Balaguru

Reputation: 7842

Tools like nmap can help in determining whether the particular port is open or closed.

TCP : nmap uses techniques like TCP SYN scan or TCP Connect scan where the server will reply with ACK-RST packet for SYN request incase of closed port. You can notice that, it is determined at the time of 3-way handshake (connection establishment) itself.

UDP : nmap also facilitates the UDP scan, where ICMP based 'Port Unreachable' packet shall be returned in case the UDP packet arrives on a closed UDP port (This also depends on the stack in the OS). Unlike TCP, the UDP is not a connection-based protocol and ICMP is also connection-less, so you might need to send some significant number of UDP packets for a short interval and evaluate based on the responses or some similar logic.

You can arrive on similar technique/logic and determine whether the particular port is open or closed and flash appropriate message for user.

Upvotes: 1

Mangu Singh Rajpurohit
Mangu Singh Rajpurohit

Reputation: 11420

Try to connect on that port using socket.connect(), if connection is not successful, then show message that Port not opened.

Upvotes: 3

Related Questions