Python network programming
sorry took so long. i completely forgot about it.
here's the code:```markup#/usr/bin/python #/usr/bin/env python import os,sys import platform as posix import random import socket import SocketServer host = raw_input("enter target address: ") host = raw_input("go through port no: ") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in sys.argv: if i == "-g": g_flag = True elif i == -h: h_opt = sys.argv.pop(sys,argv.index("-h")) socket.connect((h, 22))
can anyone check the code for me and fix it?
read my article on sockets in python.
Or
def __init__(self, port):
self.port = port
threading.Thread.__init__(self)
def run(self):
self.host = ''
self.addr = (self.host, self.port)
self.buf = 1024
sock = None
for res in getaddrinfo(self.host, self.port, AF_UNSPEC, SOCK_STREAM, 0, AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
sock = socket(af, socktype, proto)
except error, msg:
sock = None
continue
try:
sock.bind(sa) #the same as our old server, but implemented as a thread
sock.listen(1)
except error, msg:
sock.close()
sock = None
continue
break
if sock is None:
raise RuntimeError, "could not open socket"
self.sock,addr = sock.accept()
self.mainloop()
def mainloop(self):
while 1:
data = self.sock.recv(self.buf)
if not data:
print "Remote user has terminated the session."
break
else:
print 'remote_user:',data
print "message?:"
del data
self.close()
def close(self):
self.sock.shutdown(SHUT_RDWR)
self.sock.close()```
Note: this was a moassive thing, i had imported socket to local namespace, you'll need to either (from socket import *) or (import socket) and append socket. to the back most of that...
Oh wait... did you want a client?
```markupclass SockClient(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.addr = (self.host, self.port)
sock = None
for res in getaddrinfo(self.host, self.port, AF_UNSPEC, SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
sock = socket(af, socktype, proto)
except error, msg:
sock = None
continue
try:
sock.connect(sa) #the same as our old client
except error, msg:
sock.close()
sock = None
continue
break
if sock is None:
raise RuntimeError, "could not connect socket"
self.sock = sock
def recv(self,buf=1024):
return self.sock.recv(buf)
def send(self,msg):
self.sock.send("%s\n" % (msg))
del msg
def close(self):
self.sock.shutdown(SHUT_RDWR)
self.sock.close()```
richohealey: I know, the lack of tabs really annoy me. Python looks so ugly without indentation. Like basic.
As for the original code, I'm sorry to say there are several errors in this. socket.connect((h, 22)) is the main problem, though not the only one. This is the first time h is mentioned, and I think you mean sock.connect.