I am trying to open multiple ports in a computer with PYTHON Sockets.

Here is my code..

import socket
import thread
from threading import *
BUFSIZ = 1024
clientsock = socket.socket()
def handler(clientsock,addr):
    while 1:
        data = clientsock.recv(BUFSIZ)
        if not data:
            break
def function():
	for n in range(1,5):
		var = 's'+str(n)
		clientsock, addr = var.accept()
		thread.start_new_thread(handler, (clientsock, addr))
		return
for port in range(1,5):
	var = 's'+str(port)
	var = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	HOST = socket.gethostname()
	var.bind((HOST,port))
	var.listen(5)
while 1:
	print 'Waiting for connection:'
	function()

I am getting following error:

C:\Python27>python a2.py
Waiting for connection:
Traceback (most recent call last):
  File "a2.py", line 25, in <module>
    function()
  File "a2.py", line 14, in function
    clientsock, addr = var.accept()
AttributeError: 'str' object has no attribute 'accept'

C:\Python27>

What wrong in the code???
Any other way to do the same job.

What you want to do with that strange line as strings have not method called accept?

I think It will accept the connection.I think i have made some mistake.Please clarify this.

for n = 1
s1= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
and clientsock, addr = s1.accept()

I wanted to do smiler thing.

Now with proper formating :-(


# ------------------------------------

import socket
import thread
from threading import *

BUFSIZ = 1024
clientsock = socket.socket()
def handler(clientsock,addr):
	while 1:
		data = clientsock.recv(BUFSIZ)
		if not data:
			break
class mysock(object):
	s1=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s2=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s3=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s4=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s5=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def function():
	for n in range(1,5):
		var = getattr(mysock,'s'+str(n))
		clientsock, addr = var.accept()
		thread.start_new_thread(handler, (clientsock, addr))
		return

for port in range(1,5):
	var = getattr(mysock,'s'+str(port))
	HOST = socket.gethostname()
	var.bind((HOST,port))
	var.listen(5)


print 'Waiting for connection:'
function()

# ----------------------
AB

You really shouldn't use those ports. You should use a really high arbitrary four digit port for personal use. The lower ones are reserved for services and such.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.