What host to use when making a UDP socket in python?

10,722

Solution 1

The host argument is the host IP you want to bind to. Specify the IP of one of your interfaces (Eg, your public IP, or 127.0.0.1 for localhost), or use 0.0.0.0 to bind to all interfaces. If you bind to a specific interface, your service will only be available on that interface - for example, if you want to run something that can only be accessed via localhost, or if you have multiple IPs and need to run different servers on each.

Solution 2

"0.0.0.0" will listen for all incoming hosts. For example,

sock.bind(("0.0.0.0", 999))
data,addr = sock.recv(1024)

Solution 3

Use:

sock.bind(("", 999))
Share:
10,722
c0m4
Author by

c0m4

B.Sc from Mariestad, Sweden. Works with embedded software. I live in an 100 year old house with my wife and two daughters. I like C and python.

Updated on June 04, 2022

Comments

  • c0m4
    c0m4 almost 2 years

    I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python:

    import socket
    import sys
    
    HOST = ??????? 
    PORT = 80
    
    
    # SOCK_DGRAM is the socket type to use for UDP sockets
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    sock.bind((HOST,PORT))
    data,addr = sock.recv(1024)
    print "Received: %s" % data
    print "Addr: %s" % addr 
    

    What should I use as host? I know the IP of the sender but it seems anything thats not local gives me socket.error: [Errno 10049]. The IP that the VPN gives me (the same IP that the sender sends to, that is)? Or just localhost?

  • c0m4
    c0m4 about 15 years
    So 'bind to this IP' means 'listen for data sent to this IP'?
  • c0m4
    c0m4 about 15 years
    Why are you using port 999? Just an example or should I use port 999 as well?
  • bortzmeyer
    bortzmeyer about 15 years
    To bind to all local IP addresses, I find socket.INADDR_ANY clearer than 0.0.0.0.
  • Lance Richardson
    Lance Richardson almost 14 years
    You're correct. I generally test even trivial code fragments before posting, I guess I didn't in this case. The correct way to bind to INADDR_ANY in Python is to pass an empty string for the host address part of the tuple. I'll correct my answer, thanks for pointing that out.