Stian
Stian

Reputation: 669

Socket gives me error when i try to connect -python

im trying to learn about sockets and i cant manage to connect to the ip,port. this is the script i got:

stian's socket test tool

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

Answers (3)

Some programmer dude
Some programmer dude

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

Tom van der Woerdt
Tom van der Woerdt

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

St&#233;phane Glondu
St&#233;phane Glondu

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

Related Questions