Initial import
[ldd.git] / ldd / mdns.py
1 #    ldd - DNS implementation in Python
2 #    Copyright (C) 2006 Fredrik Tolf <fredrik@dolda2000.com>
3 #
4 #    This program is free software; you can redistribute it and/or modify
5 #    it under the terms of the GNU General Public License as published by
6 #    the Free Software Foundation; either version 2 of the License, or
7 #    (at your option) any later version.
8 #
9 #    This program is distributed in the hope that it will be useful,
10 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 #    GNU General Public License for more details.
13 #
14 #    You should have received a copy of the GNU General Public License
15 #    along with this program; if not, write to the Free Software
16 #    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 import socket
19 import struct
20
21 ip4addr = "224.0.0.251"
22 ip6addr = "ff02::fb"
23
24 def mkip4sock(port = 5353):
25     sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
26     mcastinfo = socket.inet_pton(socket.AF_INET, ip4addr)
27     mcastinfo += socket.inet_pton(socket.AF_INET, "0.0.0.0")
28     sk.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, mcastinfo)
29     sk.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 255)
30     sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
31     sk.bind(("", port))
32     return sk
33
34 def mkip6sock(port = 5353):
35     sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
36     mcastinfo = socket.inet_pton(socket.AF_INET6, ip6addr)
37     mcastinfo += struct.pack("I", 0)
38     sk.setsockopt(socket.SOL_IP, socket.IPV6_JOIN_GROUP, mcastinfo)
39     sk.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, 255)
40     sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
41     sk.bind(("", port))
42     return sk