[Tutor] Socket Programming

Kushal Kumaran kushal.kumaran+python at gmail.com
Mon Apr 8 15:37:58 CEST 2013


Mousumi Basu <mousumi251 at gmail.com> writes:

> I want to perform binding between two computers having ip addresses
> 172.18.2.11 and  172.18.2.95.So i wrote the following code(on the computer
> having IP address 172.18.2.95):-
>
>
> import socket
> import sys
> s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
> try:
>     s=s.bind(('172.18.2.11',2213))

The bind method does not do what you think it does.

To bind to an IP address, the address must be assigned to one of the
interfaces on the host where the code is running.  So your bind call
will not work on 172.18.2.95.  It will only work on 172.18.2.11.  To
make a connection to a different host, you call the connect method.

Since you are using SOCK_DGRAM, an explicit connect call is not
required.  You can just call the sendto method on the socket.  On the
other end, the socket will need the bind method to be called.  It can
then call recvfrom to receive data.

You should read an introductory sockets programming text if you intend
to use the python socket module.
This page: http://beej.us/guide/bgnet/output/html/multipage/index.html
which showed up in my web search, seems simple.  You will have to
translate C code to python, but the basic concepts will apply.

>     print 'socket bind is complete'
> except socket.error,msg:
>     print 'bind failed'
>     sys.exit()
>
>
> The output is :-
> bind failed
>
>
> but when i am writting;-
>
> s=s.bind(('localhost',2213))
>
> the output is;-
> socket bind is complete
>
>
>
> Can you please tell me where i am making the error?
> (The computers are connected as the ping operation is executing properly in
> command prompt)

-- 
regards,
kushal


More information about the Tutor mailing list