I am implementing a raw socket program in python and I came across bind() where I can bind my socket to the interface. As I understand it, the first field for this function is the interface I wish to bind to. What is the second field? Is this the Ethertype (such as IP4)? In the raw socket example found in the Python reference docs the code looks like this:
# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))
Why is the second field zero? In other examples I have seen this is frequently set to 0x0800 (or 2048 in decimal) leading me to believe that this is possibly setting the socket to an IP4 protocol. I have also seen this set to 9999. Perhaps I am missing/misunderstanding something here.
The second field indicates the port number you are binding to. Set it to 0 however, will let the OS pick an available port for you from range 1024 to 65535.
You can then get the port that was chosen by
sock.getsockname()[1].Also, setting the first field (host) to
0.0.0.0or''will allow accepting connections from any IPv4 address.Edit: As @highlycaffeinated pointed out, the above is true because
socket.AF_INETaddress family is chosen. If however, socket.AF_INET6 is chosen, the format will be(host, port, flowinfo, scopeid).