Open a UDP socket, bind it to a port and select a multicast group.
339999
def mcast_receiver(port, mcgroup=MC_GROUP):
    

    if _is_broadcast_group(mcgroup):
        group = None
    else:
        group = mcgroup

    # Create a socket
    sock = socket(AF_INET, SOCK_DGRAM)

    # Allow multiple copies of this program on one machine
    # (not strictly needed)
    sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    if group:
        sock.setsockopt(SOL_IP, IP_MULTICAST_TTL, TTL_LOCALNET)  # default
        sock.setsockopt(SOL_IP, IP_MULTICAST_LOOP, 1)  # default

    # Bind it to the port
    sock.bind(('', port))

    # Look up multicast group address in name server
    # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
    if group:
        group = gethostbyname(group)

        # Construct binary group address
        bytes_ = [int(b) for b in group.split(".")]
        grpaddr = 0
        for byte in bytes_:
            grpaddr = (grpaddr << 8) | byte

        # Construct struct mreq from grpaddr and ifaddr
        ifaddr = INADDR_ANY
        mreq = struct.pack('!LL', grpaddr, ifaddr)

        # Add group membership
        sock.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)

    return sock, group or '<broadcast>'
888003
def send(self, packet, retry=True):
        """"""
        addr = ('255.255.255.255', self.port)  # 255. is the broadcast IP for UDP
        try:
            self.send_socket.sendto(packet, addr)
        except Exception as e:
            self.log("Link failed to send packet over socket %s" % e)
            sleep(0.2)
            if retry:
                self.send(packet, retry=False)
1162266
def get_free_udp_port():
    '''
    
    '''
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 0))
    addr = sock.getsockname()
    sock.close()
    return addr[1]
1305883
static SocketChannelUDT newConnectorChannelUDT(final TypeUDT type) {
        try {
            return SelectorProviderUDT.from(type).openSocketChannel();
        } catch (final IOException e) {
            throw new ChannelException("failed to open a socket channel", e);
        }
    }
1313358
def server_bind(self):
        """"""
        socketserver.TCPServer.server_bind(self)
        host, port = self.socket.getsockname()[:2]
        self.server_name = socket.getfqdn(host)
        self.server_port = port
1205012
def new_port():
    """"""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
    for i in range(12042, 16042):
        try:
            s.bind(('127.0.0.1', i))
            s.close()
            return i
        except socket.error:
            pass
    raise Exception('No local port available')
1058331
def _initsocket(self):
        """"""
        self.send_socket = socket(AF_INET, SOCK_DGRAM)
        self.send_socket.setblocking(0)
        self.send_socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

        self.recv_socket = socket(AF_INET, SOCK_DGRAM)
        self.recv_socket.setblocking(0)
        if IS_BSD:
            self.recv_socket.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)  # requires sudo
        self.recv_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)  # allows multiple UDPLinks to all listen for UDP packets
        self.recv_socket.bind(('', self.port))
636854
def bind_port(requested_port):
  """"""
  sockets = tornado.netutil.bind_sockets(requested_port)

  if requested_port != 0:
    return sockets, requested_port

  # Get the actual port number.
  for s in sockets:
    host, port = s.getsockname()[:2]
    if host == '0.0.0.0':
      return sockets, port

  raise RuntimeError('Could not determine the bound port.')
597718
function submit(packet) {

	var buffer;

	if (!udpIp) {
		throw new Error('No multicast_ipv4 ip address has been set');
	}

	if (!bound) {
		return alchemy.initMulticast(function delayedSend() {
			submit(packet);
		});
	}

	alchemy.setStatus('multicast_submits', ++submits);

	// Set the packet origin
	packet.origin = alchemy.discovery_id;

	// Set the server http port
	packet.http_port = alchemy.settings.port;

	// Serialize the buffer
	buffer = bson.serialize(packet);

	// Transmit the buffer
	server.send(buffer, 0, buffer.length, udpPort, udpIp, function callback(err) {

		if (err) {
			log.error('Multicast error:', err);
			alchemy.setStatus('multicast_errors', ++errors);

			if (err.code == 'EMSGSIZE') {
				maxSize = ~~(maxSize * 0.9);
				alchemy.setStatus('multicast_maxsize', maxSize);
			}
		}
	});
}
852826
def open_socket(host, port) # :nodoc:
      return Timeout.timeout(@open_timeout, Net::OpenTimeout) {
        if defined? SOCKSSocket and ENV["SOCKS_SERVER"]
          @passive = true
          sock = SOCKSSocket.open(host, port)
        else
          sock = TCPSocket.open(host, port)
        end
        io = BufferedSocket.new(sock)
        io.read_timeout = @read_timeout
        io
      }
    end
76203
public void bindAndStart(int port) throws Exception {
        server = new NioServer(new StreamConnectionFactory() {
            @Override
            public ProtobufConnection<Protos.TwoWayChannelMessage> getNewConnection(InetAddress inetAddress, int port) {
                return new ServerHandler(new InetSocketAddress(inetAddress, port), timeoutSeconds).socketProtobufHandler;
            }
        }, new InetSocketAddress(port));
        server.startAsync();
        server.awaitRunning();
    }
1229184
def _check_port(host, port, socket_type):
        
        if socket_type == "UDP":
            socket_type = socket.SOCK_DGRAM
        else:
            socket_type = socket.SOCK_STREAM

        for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket_type, 0, socket.AI_PASSIVE):
            af, socktype, proto, _, sa = res
            with socket.socket(af, socktype, proto) as s:
                s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                s.bind(sa)  # the port is available if bind is a success
            return True
490923
def start_server(port):
    '''  '''
    s = socket(AF_INET, SOCK_STREAM)
    s.settimeout(None)

    try:
        from socket import SO_REUSEPORT
        s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
    except ImportError:
        s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

    s.bind(('', port))
    pydev_log.info("Bound to port :%s", port)

    try:
        s.listen(1)
        newSock, _addr = s.accept()
        pydev_log.info("Connection accepted")
        # closing server socket is not necessary but we don't need it
        s.shutdown(SHUT_RDWR)
        s.close()
        return newSock

    except:
        pydev_log.exception("Could not bind to port: %s\n", port)
909468
def run(self):
    """"""
    self._live = True
    self._sock.settimeout(self.LISTEN_TIMEOUT_S)

    # Passing in INADDR_ANY means the kernel will choose the default interface.
    # The localhost address is used to receive messages sent in "local_only"
    # mode and the default address is used to receive all other messages.
    for interface_ip in (socket.INADDR_ANY, LOCALHOST_ADDRESS):
      self._sock.setsockopt(
          socket.IPPROTO_IP,
          socket.IP_ADD_MEMBERSHIP,
          # IP_ADD_MEMBERSHIP takes the 8-byte group address followed by the IP
          # assigned to the interface on which to listen.
          struct.pack('!4sL', socket.inet_aton(self.address), interface_ip))

    if sys.platform == 'darwin':
      self._sock.setsockopt(socket.SOL_SOCKET,
                            socket.SO_REUSEPORT,
                            1)  # Allow multiple listeners to bind.
    else:
      self._sock.setsockopt(socket.SOL_SOCKET,
                            socket.SO_REUSEADDR,
                            1)  # Allow multiple listeners to bind.
    self._sock.bind((self.address, self.port))

    while self._live:
      try:
        data, address = self._sock.recvfrom(MAX_MESSAGE_BYTES)
        data = data.decode('utf-8')
        log_line = 'Received multicast message from %s: %s' % (address, data)
        response = self._callback(data)
        if response is not None:
          log_line += ', responding with %s bytes' % len(response)
          # Send replies out-of-band instead of with the same multicast socket
          # so that multiple processes on the same host can listen for
          # requests and reply (if they all try to use the multicast socket
          # to reply, they conflict and this sendto fails).
          response = response.encode('utf-8')
          socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(
              response, address)
        _LOG.debug(log_line)
      except socket.timeout:
        pass
      except socket.error:
        _LOG.debug('Error receiving multicast message', exc_info=True)
972067
def _init_socket(self):
        """"""
        # destroy the connection if it already exists
        if self.ddpsocket:
            self.ddpsocket.remove_all_listeners('received_message')
            self.ddpsocket.remove_all_listeners('closed')
            self.ddpsocket.remove_all_listeners('opened')
            self.ddpsocket.close_connection()
            self.ddpsocket = None

        # create a ddp socket and subscribe to events
        self.ddpsocket = DDPSocket(self.url, self.debug)
        self.ddpsocket.on('received_message', self.received_message)
        self.ddpsocket.on('closed', self.closed)
        self.ddpsocket.on('opened', self.opened)
398042
function() {
  var udpServer = dgram.createSocket('udp4');
  // binding required for getting responses
  udpServer.bind();
  udpServer.on('error', function () {});
  getUdpServer = function() {
    return udpServer;
  };
  return getUdpServer();
}
905348
def bind(self, family, type, proto=0):
        """"""
        sock = self.prepare_socket(
            self.bind_addr,
            family, type, proto,
            self.nodelay, self.ssl_adapter,
        )
        sock = self.socket = self.bind_socket(sock, self.bind_addr)
        self.bind_addr = self.resolve_real_bind_addr(sock)
        return sock