Reputation: 747
I am trying to hit a port of an IP address and print the status code
(i.e 200 OK , 502 Bad Gateway
etc). Suppose, let's say port 80
is open at ip address xx.xx.xx.xxx
. So, xx.xx.xx.xxx:80
should give us 200 OK
. In my code, I am using port 811450
, which is definitely not opened and no application is running there. But it is not showing any error.
import httplib
import urllib
import socket
class mysocket:
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
host = "xx.xx.xx.xxx"
port = "811450"
def connect(self, host, port):
self.sock.connect((host, port))
def mysend(self, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
def myreceive(self):
chunks = []
bytes_recd = 0
while bytes_recd < MSGLEN:
chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
if chunk == '':
raise RuntimeError("socket connection broken")
chunks.append(chunk)
bytes_recd = bytes_recd + len(chunk)
return ''.join(chunks)
What is the recommended way to achieve it.
Upvotes: 0
Views: 1517
Reputation: 10220
First of all, 811450 isn't a valid port. The largest valid TCP port range is 65535.
Second, you're mixing up the TCP protocol and the HTTP protocol. If you want an HTTP response from the socket, you need to send a valid HTTP request. You can easily do this with the requests
package:
import requests
r = requests.get('http://xx.xx.xx.xxx:811450')
print(r.status_code)
Upvotes: 1