Search code examples
pythonsocketsprotocolsresponse

Python - Connecting to random IPs and trying to get a response from the server


I have 4 peoples External IP's. I would like to connect to their IP and get a response from the server. It's weird because for every of the 4, no port on tcp protocol would connect, but every port on udp protocol, this is not the same for my own IP.

import socket, sys
socket.setdefaulttimeout(8.5)


del sys.argv[0]

def connect_send_receive(host, port):
      try:
         s = socket.socket((socket.AF_INET, socket.SOCK_DGRAM) #On the Tcp protocol, no single port would connect to one of these 4 addresses.
         s.connect((host, port))
         s.send("I want you to dammit respond me something") #packet request says it all.
         s.recv(1024) #Server response with nothing. Error here.
      except:
         print("No response")

for connect in sys.argv:
       connect_send_receive(connect, 80)

My question is clear. 1. How do I get the server to give me a response, and after that. 2. why in 4 random people can I can only connect with udp protocol. I tried every port on tcp but no connection, and why with myself even if I go on a different IP I could connect to myself with tcp protocol.

Note: Http requests dont work on these 4 IPs.


Solution

  • TCP is a connection-based protocol. A specific "handshake" must happen to establish that connection. If no service is listening on the TCP port you try to connect to (or if a firewall is filtering connections to that port and your host doesn't pass the filter), then you will simply get a TCP reset from the system that rejects the request.

    UDP is a connectionless protocol. There is no response when a packet is sent unless the application on the server is designed to send one. If the UDP port is filtered or no service is listening on it, the packet is quietly dropped -- with no indication to the sender.

    As for your code, SOCK_DGRAM is a datagram (UDP) socket. You need to use a STREAM socket to connect to a TCP service.