Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sendto() not working on 3.1 (works on 2.6)

For some reason, the following seems to work perfectly on my ubuntu machine running python 2.6 and returns an error on my windows xp box running python 3.1

from socket import socket, AF_INET, SOCK_DGRAM
data = 'UDP Test Data'
port = 12345
hostname = '192.168.0.1'
udp = socket(AF_INET,SOCK_DGRAM)
udp.sendto(data, (hostname, port))

Below is the error that the python 3.1 throws:

Traceback (most recent call last):
  File "sendto.py", line 6, in <module>
    udp.sendto(data, (hostname, port))
TypeError: sendto() takes exactly 3 arguments (2 given)

I have consulted the documentation for python 3.1 and the sendto() only requires two parameters. Any ideas as to what may be causing this?

like image 744
mozami Avatar asked Dec 29 '22 17:12

mozami


1 Answers

In Python 3, the string (first) argument must be of type bytes or buffer, not str. You'll get that error message if you supply the optional flags parameter. Change data to:

data = b'UDP Test Data'

You might want to file a bug report about that at the python.org bug tracker. [EDIT: already filed as noted by Dav]

...

>>> data = 'UDP Test Data'
>>> udp.sendto(data, (hostname, port))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sendto() takes exactly 3 arguments (2 given)
>>> udp.sendto(data, 0, (hostname, port))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sendto() argument 1 must be bytes or buffer, not str
>>> data = b'UDP Test Data'
>>> udp.sendto(data, 0, (hostname, port))
13
>>> udp.sendto(data, (hostname, port))
13
like image 73
Ned Deily Avatar answered Jan 01 '23 07:01

Ned Deily