8

I am learning networking programming and trying to grasp the basics of sockets through this example.

import socket,sys


s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

MAX = 65535
PORT = 1060

if sys.argv[1:] == ['server']:
    s.bind(('127.0.0.1',PORT))
    print 'Listening at ' , s.getsockname()
    while True:
        data,address = s.recvfrom(MAX)
        print ' The address at ' , address , ' says ' , repr(data)
        s.sendto('your data was %d bytes' % len(data),address)

elif  sys.argv[1:] == ['client']:
    print ' Address before sending ' ,s.getsockname()
    s.sendto('This is the message',('127.0.0.1',PORT))
    print ' Address after sending ' ,s.getsockname()
    data,address = s.recvfrom(MAX)
    print ' The server at ' , address , ' says ' , repr(data)

else:
    print >> sys.stderr, 'usage: udp_local.py server | client '

However,its throwing up an exception saying the arguments given by getsockname() were invalid specifically on line 22.The code is correct as far as I know.Here's the exception

Traceback (most recent call last):
  File "udp_local.py", line 23, in <module>
    print ' Address before sending ' ,s.getsockname()
  File "c:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 10022] An invalid argument was supplied

Using PyScripter 2.5.3.0 x86

4
  • A socket probably won't actually have an address before sending, unless you call bind on it first. On Mac, I don't get an error but the returned port is 0 (meaning it hasn't been assigned a port yet). Commented Mar 26, 2013 at 14:07
  • I'm using Python.The standard socket module Commented Mar 26, 2013 at 14:27
  • What platform are you on? I don't get this error on python2.7 OSX 10.8 Commented Mar 26, 2013 at 14:39
  • OK I commented the "before sending " getsockname() code out and turns out you are right, the socket won't actually have an address . Commented Mar 26, 2013 at 19:32

1 Answer 1

9

Well I got the problem.The socket doesn't have an address untill its either binded or data is sent. Just had to comment it out.

elif  sys.argv[1:] == ['client']:
 ## print ' Address before sending ' ,s.getsockname()

Thanks

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.