List of usage examples for java.net InetSocketAddress InetSocketAddress
private InetSocketAddress(int port, String hostname)
From source file:com.clustercontrol.port.protocol.ReachAddressTCP.java
/** * ????????????/*from w w w .j a v a 2s . c o m*/ * * @param addressText * @return PORT */ @Override protected boolean isRunning(String addressText) { m_message = ""; m_messageOrg = ""; m_response = -1; boolean isReachable = false; try { long start = 0; // long end = 0; // StringBuffer bufferOrg = new StringBuffer(); // String result = ""; // Reachability ?? ICMP ?? boolean retry = true; InetAddress address = InetAddress.getByName(addressText); bufferOrg.append("Monitoring the port of " + address.getHostName() + "[" + address.getHostAddress() + "]:" + m_portNo + ".\n\n"); // Socket socket = null; for (int i = 0; i < m_sentCount && retry; i++) { try { // ? socket = new Socket(); InetSocketAddress isa = new InetSocketAddress(address, m_portNo); bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: "); start = HinemosTime.currentTimeMillis(); socket.connect(isa, m_timeout); end = HinemosTime.currentTimeMillis(); m_response = end - start; if (m_response > 0) { if (m_response < m_timeout) { result = ("Response Time = " + m_response + "ms"); } else { m_response = m_timeout; result = ("Response Time = " + m_response + "ms"); } } else { result = ("Response Time < 1ms"); } retry = false; isReachable = true; } catch (BindException e) { result = (e.getMessage() + "[BindException]"); retry = true; isReachable = false; } catch (ConnectException e) { result = (e.getMessage() + "[ConnectException]"); retry = false; isReachable = false; } catch (NoRouteToHostException e) { result = (e.getMessage() + "[NoRouteToHostException]"); retry = true; isReachable = false; } catch (PortUnreachableException e) { result = (e.getMessage() + "[PortUnreachableException]"); retry = true; isReachable = false; } catch (IOException e) { result = (e.getMessage() + "[IOException]"); retry = true; isReachable = false; } finally { bufferOrg.append(result + "\n"); if (socket != null) { try { socket.close(); } catch (IOException e) { m_log.warn("isRunning(): " + "socket close failed: " + e.getMessage(), e); } } } if (i < m_sentCount - 1 && retry) { try { Thread.sleep(m_sentInterval); } catch (InterruptedException e) { break; } } } m_message = result + "(TCP/" + m_portNo + ")"; m_messageOrg = bufferOrg.toString(); return isReachable; } catch (UnknownHostException e) { m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + e.getMessage()); m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage() + ")"; return false; } }
From source file:org.devtcg.five.util.streaming.LocalHttpServer.java
public void bind(int port) throws IOException { bind(new InetSocketAddress(InetAddress.getLocalHost(), port)); }
From source file:com.datatorrent.stram.engine.StreamContext.java
public InetSocketAddress getBufferServerAddress() { InetSocketAddress isa = get(BUFFER_SERVER_ADDRESS); return new InetSocketAddress(isa.getHostName(), isa.getPort()); }
From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java
private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways) throws IOException, InterruptedException { Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses(); List<DatagramChannel> channels = new ArrayList<>(); final Map<DatagramChannel, InetAddress> bindMap = Collections .synchronizedMap(new HashMap<DatagramChannel, InetAddress>()); final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections .synchronizedMap(new HashMap<InetAddress, InetAddress>()); try {/*from w ww . java2s .c o m*/ for (InetAddress localAddress : localAddresses) { DatagramChannel unicastChannel = null; try { unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } channels.add(unicastChannel); bindMap.put(unicastChannel, localAddress); } } catch (IOException ioe) { for (DatagramChannel channel : channels) { IOUtils.closeQuietly(channel); } throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(channels); communicator.startAsync().awaitRunning(); communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { // make sure version is 2 and error isn't ADDRESS_MISMATCH and we're good to go if (packet.remaining() < 4 || packet.get(0) == 2 && packet.get(4) == PcpResultCode.ADDRESS_MISMATCH.ordinal()) { return; } InetAddress localAddress = bindMap.get(channel); if (localAddress == null) { return; } localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress()); } }); for (DatagramChannel channel : bindMap.keySet()) { for (InetAddress gateway : gateways) { ByteBuffer outBuf = ByteBuffer.allocate(1100); MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0, InetAddress.getByName("::"), 0L); mpr.dump(outBuf, bindMap.get(channel)); outBuf.flip(); communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer()); } } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } return new HashMap<>(localAddrToGatewayAddrMap); }
From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.java
private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways) throws IOException, InterruptedException { Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses(); List<DatagramChannel> channels = new ArrayList<>(); final Map<DatagramChannel, InetAddress> bindMap = Collections .synchronizedMap(new HashMap<DatagramChannel, InetAddress>()); final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections .synchronizedMap(new HashMap<InetAddress, InetAddress>()); try {//from w w w .ja v a 2 s . co m for (InetAddress localAddress : localAddresses) { DatagramChannel unicastChannel = null; try { unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } channels.add(unicastChannel); bindMap.put(unicastChannel, localAddress); } } catch (IOException ioe) { for (DatagramChannel channel : channels) { IOUtils.closeQuietly(channel); } throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(channels); communicator.startAsync().awaitRunning(); communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { new ExternalAddressNatPmpResponse(packet); // should error out if not valid InetAddress localAddress = bindMap.get(channel); if (localAddress == null) { return; } localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress()); } }); ByteBuffer outBuf = ByteBuffer.allocate(16); ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest(); eanpr.dump(outBuf); outBuf.flip(); for (DatagramChannel channel : bindMap.keySet()) { for (InetAddress gateway : gateways) { communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer()); } } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } return new HashMap<>(localAddrToGatewayAddrMap); }
From source file:com.pinterest.rocksplicator.controller.tasks.RemoveHostTask.java
@Override public void process(Context ctx) throws Exception { final String clusterName = ctx.getCluster(); final HostBean toRemove = getParameter().getHostToRemove(); final Admin.Client client = clientFactory.getClient(toRemove); InetSocketAddress hostAddr = new InetSocketAddress(toRemove.getIp(), toRemove.getPort()); // 1) if it's not forceRemoval, ping the host to remove to make sure it's not running if (!getParameter().getForceRemoval()) { try {//from ww w .j av a 2 s. c om client.ping(); LOG.error("Host {} is still alive!", hostAddr); // if we reach here, it means the process is still alive as #ping() succeeded. ctx.getTaskQueue().failTask(ctx.getId(), "Host is still alive!"); return; } catch (TException tex) { // continue if #ping() failed. } } // 2) update cluster config to reflect the change ClusterBean clusterBean = ZKUtil.getClusterConfig(zkClient, clusterName); if (clusterBean == null) { LOG.error("Failed to get config for cluster {}.", clusterName); ctx.getTaskQueue().failTask(ctx.getId(), "Failed to read cluster config from zookeeper."); return; } for (SegmentBean segmentBean : clusterBean.getSegments()) { // filter out the host to remove List<HostBean> newHostList = segmentBean.getHosts().stream() .filter(hostBean -> !(hostBean.getIp().equals(toRemove.getIp()) && hostBean.getPort() == toRemove.getPort())) .collect(Collectors.toList()); segmentBean.setHosts(newHostList); } ZKUtil.updateClusterConfig(zkClient, clusterBean); LOG.info("Updated config to {}", ConfigParser.serializeClusterConfig(clusterBean)); ctx.getTaskQueue().finishTask(ctx.getId(), "Successfully removed host " + toRemove.getIp() + ":" + toRemove.getPort()); }
From source file:ru.codemine.ccms.counters.kondor.KondorClient.java
private File ftpDownload(Shop shop) { String login = settingsService.getCountersKondorFtpLogin(); String pass = settingsService.getCountersKondorFtpPassword(); String ip = shop.getProvider().getIp(); String tmpFileName = settingsService.getStorageRootPath() + DateTime.now().toString("YYYYMMdd-s" + shop.getId()); try {//from w w w.j a v a2 s.c o m log.debug("Starting ftp session..."); Socket manageSocket = new Socket(); manageSocket.connect(new InetSocketAddress(ip, 21), 3000); BufferedReader in = new BufferedReader(new InputStreamReader(manageSocket.getInputStream())); PrintWriter out = new PrintWriter(manageSocket.getOutputStream(), true); String ftpAnswer; ftpAnswer = in.readLine(); log.debug("FTP greetings: " + ftpAnswer); out.println("USER " + login); ftpAnswer = in.readLine(); log.debug("FTP USER command responce: " + ftpAnswer); out.println("PASS " + pass); String afterAuth = in.readLine(); log.debug("FTP PASS command responce: " + afterAuth); out.println("PASV"); String pasvResponce = in.readLine(); log.debug("FTP: PASV command responce: " + pasvResponce); if (pasvResponce.startsWith("227 (")) { pasvResponce = pasvResponce.substring(5); List<String> parsedPasv = new ArrayList<>(Arrays.asList(pasvResponce.split(","))); String p4 = parsedPasv.get(4); String p5 = parsedPasv.get(5).replace(")", ""); int port = Integer.parseInt(p4) * 256 + Integer.parseInt(p5); log.debug("FTP: Recieved port: " + port); Socket dataSocket = new Socket(); dataSocket.connect(new InetSocketAddress(ip, port), 3000); InputStream dataIn = dataSocket.getInputStream(); FileOutputStream dataOut = new FileOutputStream(tmpFileName); out.println("RETR total.dbf"); ftpAnswer = in.readLine(); log.debug("FTP RETR command responce: " + ftpAnswer); IOUtils.copy(dataIn, dataOut); dataOut.flush(); dataOut.close(); dataSocket.close(); } else { if (afterAuth.startsWith("530")) { log.warn( " ?, : " + shop.getName()); } else { log.warn( " ? PASV, : " + shop.getName()); } } out.println("QUIT"); ftpAnswer = in.readLine(); log.debug("FTP QUIT command responce: " + ftpAnswer); manageSocket.close(); } catch (Exception e) { log.warn( "? ? ? " + shop.getName() + ", : " + e.getMessage()); } return new File(tmpFileName); }
From source file:de.flapdoodle.embed.memcached.MemcachedExecutableTest.java
@Test public void testStartStopTenTimesWithNewMemcacheExecutable() throws IOException, InterruptedException { boolean useMemcache = true; int loops = 10; MemcachedConfig memcachedConfig = new MemcachedConfig(Version.Main.PRODUCTION, 12345); IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(Command.MemcacheD).build(); for (int i = 0; i < loops; i++) { _logger.info("Loop: " + i); MemcachedExecutable memcachedExe = MemcachedStarter.getInstance(runtimeConfig).prepare(memcachedConfig); try {//from w w w .ja va 2s . co m MemcachedProcess memcached = memcachedExe.start(); if (useMemcache) { MemcachedClient jmemcache = new MemcachedClient(new InetSocketAddress("localhost", 12345)); // adding a new key jmemcache.add("key", 5, "value"); // getting the key value assertEquals("value", jmemcache.get("key")); } memcached.stop(); } finally { memcachedExe.stop(); Thread.sleep(500); } } }
From source file:gridool.util.xfer.TransferUtils.java
public static void sendfile(@Nonnull final File file, final long fromPos, final long count, @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort, final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler) throws IOException { if (!file.exists()) { throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist"); }// ww w . j a va 2s .com if (!file.isFile()) { throw new IllegalArgumentException(file.getAbsolutePath() + " is not file"); } if (!file.canRead()) { throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read"); } final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort); SocketChannel channel = null; Socket socket = null; final OutputStream out; try { channel = SocketChannel.open(); socket = channel.socket(); socket.connect(dstSockAddr); out = socket.getOutputStream(); } catch (IOException e) { LOG.error("failed to connect: " + dstSockAddr, e); IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); throw e; } DataInputStream din = null; if (sync) { InputStream in = socket.getInputStream(); din = new DataInputStream(in); } final DataOutputStream dos = new DataOutputStream(out); final StopWatch sw = new StopWatch(); FileInputStream src = null; final long nbytes; try { src = new FileInputStream(file); FileChannel fc = src.getChannel(); String fileName = file.getName(); IOUtils.writeString(fileName, dos); IOUtils.writeString(writeDirPath, dos); long xferBytes = (count == -1L) ? fc.size() : count; dos.writeLong(xferBytes); dos.writeBoolean(append); // append=false dos.writeBoolean(sync); if (handler == null) { dos.writeBoolean(false); } else { dos.writeBoolean(true); handler.writeAdditionalHeader(dos); } // send file using zero-copy send nbytes = fc.transferTo(fromPos, xferBytes, channel); if (LOG.isDebugEnabled()) { LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to " + dstSockAddr.toString() + " in " + sw.toString()); } if (sync) {// receive ack in sync mode long remoteRecieved = din.readLong(); if (remoteRecieved != xferBytes) { throw new IllegalStateException( "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes"); } } } catch (FileNotFoundException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw e; } catch (IOException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw e; } finally { IOUtils.closeQuietly(src); IOUtils.closeQuietly(din, dos); IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); } }