Reputation: 669
im trying to learn about sockets and i cant manage to connect to the ip,port. this is the script i got:
import socket
print "send request to website to check if sockets work right"
ip = raw_input("website ip: ")
port = raw_input("website port: ")
socket.connect(ip, port)
tosend = "this is a test"
currVal = 0
while currVal < 1:
socket.send(tosend)
print "1 sockets sent..."
currrVal += 1
print "Done sending sockets. This hopefully worked"
is anything wrong with the python code? does this only work with ipv4 or ipv6? or does it work with both?
ERROR IM GETTING:
C:\Users\Swipper\Documents\Python\sockets>sock.py
send request to website to check if sockets work right
website ip: 127.0.0.1
website port:
Traceback (most recent call last):
File "C:\Users\Swipper\Documents\Python\sockets\sock.py", line 8, in <modu
le>
socket.connect(ip, port)
AttributeError: 'module' object has no attribute 'connect'
hope someone know the answer.
PS: I Use python 2.7!
-stian
Upvotes: 1
Views: 3434
Reputation: 409136
Shouldn't the argument to the connect call be a tuple?
socket.connect((ip, port))
And check the return value of the send
call.
Also, you won't get to know if the other end closed connection unless you receive something. Receiving is the only sure way to know if the connection has been closed.
Edit: And like the others say, you have to create a socket object.
Upvotes: 0
Reputation: 29965
You're calling .connect()
on the module instead of an object. You will have to instantiate a socket object first, which is normally achieved via socket.socket()
. You can then call .connect()
on the object that is returned.
s = socket.socket()
s.connect((ip, int(port))
Upvotes: 4
Reputation: 670
You must first create a socket object:
s = socket.socket()
s.connect((ip, int(port))
instead of:
socket.connect(ip, port)
Then use s.send
, etc.
Upvotes: 2