Search in sources :

Example 11 with DatagramSocket

use of java.net.DatagramSocket in project hadoop by apache.

the class TestPortmap method testRegistration.

@Test(timeout = 1000)
public void testRegistration() throws IOException, InterruptedException {
    XDR req = new XDR();
    RpcCall.getInstance(++xid, RpcProgramPortmap.PROGRAM, RpcProgramPortmap.VERSION, RpcProgramPortmap.PMAPPROC_SET, new CredentialsNone(), new VerifierNone()).write(req);
    PortmapMapping sent = new PortmapMapping(90000, 1, PortmapMapping.TRANSPORT_TCP, 1234);
    sent.serialize(req);
    byte[] reqBuf = req.getBytes();
    DatagramSocket s = new DatagramSocket();
    DatagramPacket p = new DatagramPacket(reqBuf, reqBuf.length, pm.getUdpServerLoAddress());
    try {
        s.send(p);
    } finally {
        s.close();
    }
    // Give the server a chance to process the request
    Thread.sleep(100);
    boolean found = false;
    @SuppressWarnings("unchecked") Map<String, PortmapMapping> map = (Map<String, PortmapMapping>) Whitebox.getInternalState(pm.getHandler(), "map");
    for (PortmapMapping m : map.values()) {
        if (m.getPort() == sent.getPort() && PortmapMapping.key(m).equals(PortmapMapping.key(sent))) {
            found = true;
            break;
        }
    }
    Assert.assertTrue("Registration failed", found);
}
Also used : DatagramSocket(java.net.DatagramSocket) XDR(org.apache.hadoop.oncrpc.XDR) VerifierNone(org.apache.hadoop.oncrpc.security.VerifierNone) DatagramPacket(java.net.DatagramPacket) CredentialsNone(org.apache.hadoop.oncrpc.security.CredentialsNone) Map(java.util.Map) Test(org.junit.Test)

Example 12 with DatagramSocket

use of java.net.DatagramSocket in project hbase by apache.

the class HBaseTestingUtility method available.

/**
   * Checks to see if a specific port is available.
   *
   * @param port the port number to check for availability
   * @return <tt>true</tt> if the port is available, or <tt>false</tt> if not
   */
public static boolean available(int port) {
    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    // Do nothing
    } finally {
        if (ds != null) {
            ds.close();
        }
        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
            /* should not be thrown */
            }
        }
    }
    return false;
}
Also used : DatagramSocket(java.net.DatagramSocket) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException)

Example 13 with DatagramSocket

use of java.net.DatagramSocket in project zookeeper by apache.

the class LeaderElection method lookForLeader.

/**
     * Invoked in QuorumPeer to find or elect a new leader.
     * 
     * @throws InterruptedException
     */
public Vote lookForLeader() throws InterruptedException {
    try {
        self.jmxLeaderElectionBean = new LeaderElectionBean();
        MBeanRegistry.getInstance().register(self.jmxLeaderElectionBean, self.jmxLocalPeerBean);
    } catch (Exception e) {
        LOG.warn("Failed to register with JMX", e);
        self.jmxLeaderElectionBean = null;
    }
    try {
        self.setCurrentVote(new Vote(self.getId(), self.getLastLoggedZxid()));
        // We are going to look for a leader by casting a vote for ourself
        byte[] requestBytes = new byte[4];
        ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);
        byte[] responseBytes = new byte[28];
        ByteBuffer responseBuffer = ByteBuffer.wrap(responseBytes);
        /* The current vote for the leader. Initially me! */
        DatagramSocket s = null;
        try {
            s = new DatagramSocket();
            s.setSoTimeout(200);
        } catch (SocketException e1) {
            LOG.error("Socket exception when creating socket for leader election", e1);
            System.exit(4);
        }
        DatagramPacket requestPacket = new DatagramPacket(requestBytes, requestBytes.length);
        DatagramPacket responsePacket = new DatagramPacket(responseBytes, responseBytes.length);
        int xid = epochGen.nextInt();
        while (self.isRunning()) {
            HashMap<InetSocketAddress, Vote> votes = new HashMap<InetSocketAddress, Vote>(self.getVotingView().size());
            requestBuffer.clear();
            requestBuffer.putInt(xid);
            requestPacket.setLength(4);
            HashSet<Long> heardFrom = new HashSet<Long>();
            for (QuorumServer server : self.getVotingView().values()) {
                LOG.info("Server address: " + server.addr);
                try {
                    requestPacket.setSocketAddress(server.addr);
                } catch (IllegalArgumentException e) {
                    // in order to capture this critical detail.
                    throw new IllegalArgumentException("Unable to set socket address on packet, msg:" + e.getMessage() + " with addr:" + server.addr, e);
                }
                try {
                    s.send(requestPacket);
                    responsePacket.setLength(responseBytes.length);
                    s.receive(responsePacket);
                    if (responsePacket.getLength() != responseBytes.length) {
                        LOG.error("Got a short response: " + responsePacket.getLength());
                        continue;
                    }
                    responseBuffer.clear();
                    int recvedXid = responseBuffer.getInt();
                    if (recvedXid != xid) {
                        LOG.error("Got bad xid: expected " + xid + " got " + recvedXid);
                        continue;
                    }
                    long peerId = responseBuffer.getLong();
                    heardFrom.add(peerId);
                    //if(server.id != peerId){
                    Vote vote = new Vote(responseBuffer.getLong(), responseBuffer.getLong());
                    InetSocketAddress addr = (InetSocketAddress) responsePacket.getSocketAddress();
                    votes.put(addr, vote);
                //}
                } catch (IOException e) {
                    LOG.warn("Ignoring exception while looking for leader", e);
                // Errors are okay, since hosts may be
                // down
                }
            }
            ElectionResult result = countVotes(votes, heardFrom);
            // for a dead peer                 
            if (result.numValidVotes == 0) {
                self.setCurrentVote(new Vote(self.getId(), self.getLastLoggedZxid()));
            } else {
                if (result.winner.getId() >= 0) {
                    self.setCurrentVote(result.vote);
                    // To do: this doesn't use a quorum verifier
                    if (result.winningCount > (self.getVotingView().size() / 2)) {
                        self.setCurrentVote(result.winner);
                        s.close();
                        Vote current = self.getCurrentVote();
                        LOG.info("Found leader: my type is: " + self.getLearnerType());
                        /*
                             * We want to make sure we implement the state machine
                             * correctly. If we are a PARTICIPANT, once a leader
                             * is elected we can move either to LEADING or 
                             * FOLLOWING. However if we are an OBSERVER, it is an
                             * error to be elected as a Leader.
                             */
                        if (self.getLearnerType() == LearnerType.OBSERVER) {
                            if (current.getId() == self.getId()) {
                                // This should never happen!
                                LOG.error("OBSERVER elected as leader!");
                                Thread.sleep(100);
                            } else {
                                self.setPeerState(ServerState.OBSERVING);
                                Thread.sleep(100);
                                return current;
                            }
                        } else {
                            self.setPeerState((current.getId() == self.getId()) ? ServerState.LEADING : ServerState.FOLLOWING);
                            if (self.getPeerState() == ServerState.FOLLOWING) {
                                Thread.sleep(100);
                            }
                            return current;
                        }
                    }
                }
            }
            Thread.sleep(1000);
        }
        return null;
    } finally {
        try {
            if (self.jmxLeaderElectionBean != null) {
                MBeanRegistry.getInstance().unregister(self.jmxLeaderElectionBean);
            }
        } catch (Exception e) {
            LOG.warn("Failed to unregister with JMX", e);
        }
        self.jmxLeaderElectionBean = null;
    }
}
Also used : SocketException(java.net.SocketException) Vote(org.apache.zookeeper.server.quorum.Vote) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) QuorumServer(org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) SocketException(java.net.SocketException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) HashSet(java.util.HashSet)

Example 14 with DatagramSocket

use of java.net.DatagramSocket in project zookeeper by apache.

the class QuorumPeer method startLeaderElection.

public synchronized void startLeaderElection() {
    try {
        if (getPeerState() == ServerState.LOOKING) {
            currentVote = new Vote(myid, getLastLoggedZxid(), getCurrentEpoch());
        }
    } catch (IOException e) {
        RuntimeException re = new RuntimeException(e.getMessage());
        re.setStackTrace(e.getStackTrace());
        throw re;
    }
    //}
    if (electionType == 0) {
        try {
            udpSocket = new DatagramSocket(myQuorumAddr.getPort());
            responder = new ResponderThread();
            responder.start();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }
    this.electionAlg = createElectionAlgorithm(electionType);
}
Also used : SocketException(java.net.SocketException) DatagramSocket(java.net.DatagramSocket) IOException(java.io.IOException)

Example 15 with DatagramSocket

use of java.net.DatagramSocket in project android by cSploit.

the class PacketForger method onClick.

@Override
public void onClick(View v) {
    if (!mRunning) {
        if (v.getId() == R.id.sendButton) {
            mResponse.setText("");
            mRunning = true;
            mThread = new Thread(new Runnable() {

                @Override
                public void run() {
                    int protocol = mProtocol.getSelectedItemPosition(), port = -1;
                    String data = mData.getText() + "", error = null;
                    boolean waitResponse = mWaitResponse.isChecked();
                    try {
                        port = Integer.parseInt(mPort.getText() + "".trim());
                        if (port <= 0 || port > 65535)
                            port = -1;
                    } catch (Exception e) {
                        port = -1;
                    }
                    if (port == -1)
                        error = getString(R.string.invalid_port);
                    else if (data.isEmpty())
                        error = getString(R.string.request_empty);
                    else {
                        try {
                            if (protocol == TCP_PROTOCOL) {
                                mSocket = new Socket(System.getCurrentTarget().getCommandLineRepresentation(), port);
                                OutputStream writer = mSocket.getOutputStream();
                                writer.write(data.getBytes());
                                writer.flush();
                                if (waitResponse) {
                                    BufferedReader reader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
                                    String line;
                                    final StringBuilder responseBuilder = new StringBuilder();
                                    while ((line = reader.readLine()) != null) {
                                        responseBuilder.append(line).append("\n");
                                    }
                                    final String text = responseBuilder.toString();
                                    PacketForger.this.runOnUiThread(new Runnable() {

                                        public void run() {
                                            mResponse.setText(text);
                                        }
                                    });
                                    reader.close();
                                }
                                writer.close();
                                mSocket.close();
                            } else if (protocol == UDP_PROTOCOL) {
                                mUdpSocket = new DatagramSocket();
                                DatagramPacket packet = null;
                                if (mBinaryData != null)
                                    packet = new DatagramPacket(mBinaryData, mBinaryData.length, System.getCurrentTarget().getAddress(), port);
                                else
                                    packet = new DatagramPacket(data.getBytes(), data.length(), System.getCurrentTarget().getAddress(), port);
                                mUdpSocket.send(packet);
                                if (waitResponse) {
                                    byte[] buffer = new byte[1024];
                                    DatagramPacket response = new DatagramPacket(buffer, buffer.length);
                                    mUdpSocket.receive(response);
                                    final String text = new String(buffer);
                                    PacketForger.this.runOnUiThread(new Runnable() {

                                        public void run() {
                                            mResponse.setText(text);
                                        }
                                    });
                                }
                                mUdpSocket.close();
                            }
                        } catch (Exception e) {
                            error = e.getMessage();
                        }
                    }
                    mBinaryData = null;
                    final String errorMessage = error;
                    PacketForger.this.runOnUiThread(new Runnable() {

                        public void run() {
                            Toast.makeText(PacketForger.this, getString(R.string.request_sent), Toast.LENGTH_SHORT).show();
                            setStoppedState(errorMessage);
                        }
                    });
                }
            });
            mThread.start();
        } else {
            Endpoint endpoint = System.getCurrentTarget().getEndpoint();
            byte[] mac = endpoint.getHardware();
            int i;
            if (mac != null) {
                mResponse.setText("");
                mProtocol.setSelection(UDP_PROTOCOL);
                mPort.setText("9");
                mBinaryData = new byte[6 + 16 * mac.length];
                for (i = 0; i < 6; i++) {
                    mBinaryData[i] = (byte) 0xFF;
                }
                for (i = 6; i < mBinaryData.length; i += mac.length) {
                    java.lang.System.arraycopy(mac, 0, mBinaryData, i, mac.length);
                }
                final StringBuilder hexBuilder = new StringBuilder();
                for (i = 0; i < mBinaryData.length; i++) hexBuilder.append("\\x").append(Integer.toHexString(0xFF & mBinaryData[i]).toUpperCase());
                mData.setText(hexBuilder.toString());
                Toast.makeText(this, getString(R.string.customize_wol_port), Toast.LENGTH_SHORT).show();
            } else
                Toast.makeText(this, getString(R.string.couldnt_send_wol_packet), Toast.LENGTH_SHORT).show();
        }
    } else {
        setStoppedState(null);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) OutputStream(java.io.OutputStream) Endpoint(org.csploit.android.net.Endpoint) Endpoint(org.csploit.android.net.Endpoint) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) BufferedReader(java.io.BufferedReader) Socket(java.net.Socket) DatagramSocket(java.net.DatagramSocket)

Aggregations

DatagramSocket (java.net.DatagramSocket)266 DatagramPacket (java.net.DatagramPacket)120 IOException (java.io.IOException)98 SocketException (java.net.SocketException)71 InetAddress (java.net.InetAddress)57 InetSocketAddress (java.net.InetSocketAddress)45 UnknownHostException (java.net.UnknownHostException)26 Test (org.junit.Test)25 SocketTimeoutException (java.net.SocketTimeoutException)24 InterruptedIOException (java.io.InterruptedIOException)18 PortUnreachableException (java.net.PortUnreachableException)18 BindException (java.net.BindException)16 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)16 ServerSocket (java.net.ServerSocket)14 DatagramChannel (java.nio.channels.DatagramChannel)13 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)11 MulticastSocket (java.net.MulticastSocket)10 SocketAddress (java.net.SocketAddress)8 ByteBuffer (java.nio.ByteBuffer)8 SmallTest (android.test.suitebuilder.annotation.SmallTest)5