user3217070
user3217070

Reputation:

When I import socket in python, why does it skip socket.bind?

I think every method except bind is in there. I type:

import socket
socket.bind

in the python command prompt, and get "AttributeError: 'module' object has no attribute 'bind'".

If I do:

from socket import bind

I get "ImportError: cannot import name bind"

Otherwise, dir(socket) returns 297 and everything else seems to work fine. Like I have socket.socket, socket.setsockopt, etc. Just bind doesn't exist.

I am in Mint 16 running python 2.7.5+. The same happens in python 3.3.2+, and in Python 2.7.3 on an ubuntu 12.04 vm on the same machine.

Any idea what's going on?

Upvotes: 2

Views: 2698

Answers (3)

aIKid
aIKid

Reputation: 28292

bind is a method of socket.socket, not a function in the module.

s = socket.socket(...)
s.bind()

So only once you created a socket, you can bind it to an address.

Reference: Python docs.

Hope this helps!

Upvotes: 0

mhlester
mhlester

Reputation: 23231

bind is a method of a socket object, not the module

The following is an example of where bind is used, after creating a socket object:

Taken from docs on socket

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

Upvotes: 5

TerryA
TerryA

Reputation: 59984

I might be wrong here as I don't use the socket module as often as you probably do, but it seems bind is the function of the class socket in the module socket. So to access it, you have to do:

>>> socket.socket.bind
<unbound method _socketobject.bind>

Upvotes: 0

Related Questions