public static boolean pingHost(String host, int port, int timeout) { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(host, port), timeout); return true; } catch (IOException e) { return false; // Either timeout or unreachable or failed DNS lookup. } }
public MysqlConnector(InetSocketAddress address, String username, String password){ String addr = address.getHostString(); int port = address.getPort(); this.address = new InetSocketAddress(addr, port); this.username = username; this.password = password; }
private static boolean isPortOpen(String host, Integer port) { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(InetAddress.getByName(host), port), 1000); return true; } catch (ConnectException | SocketTimeoutException e) { return false; } catch (IOException e) { throw new UncheckedIOException(e); } } }
public static void dump(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("dump".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[1024]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
public static InetSocketAddress getCliPort ( String jenkinsUrl ) throws MalformedURLException, IOException { URL u = new URL(jenkinsUrl); URLConnection conn = u.openConnection(); if ( ! ( conn instanceof HttpURLConnection ) ) { System.err.println("Not a HTTP URL"); throw new MalformedURLException(); } HttpURLConnection hc = (HttpURLConnection) conn; if ( hc.getResponseCode() >= 400 ) { System.err.println("* Error connection to jenkins HTTP " + u); } int clip = Integer.parseInt(hc.getHeaderField("X-Jenkins-CLI-Port")); return new InetSocketAddress(u.getHost(), clip); }
public void start() throws Exception { StringBuilder sb=new StringBuilder(); sb.append("\n\n----------------------- MPerf -----------------------\n"); sb.append("Date: ").append(new Date()).append('\n'); sb.append("Run by: ").append(System.getProperty("user.name")).append("\n"); System.out.println(sb); mcast_sock=new MulticastSocket(7500); sock_addr=new InetSocketAddress(InetAddress.getByName("232.5.5.5"), 7500); mcast_sock.joinGroup(InetAddress.getByName("232.5.5.5")); mcast_sock.setReceiveBufferSize(10 * 1000 * 1000); mcast_sock.setSendBufferSize(5 * 1000 * 1000); mcast_sock.setTrafficClass(8); receiver=new Receiver(); receiver.start(); }
@Override public SocketPoolable allocate(Slot slot) throws Exception { // create new InetSocketAddress to ensure name resolution is done again SocketAddress serverAddress = new InetSocketAddress(server.getHostName(), server.getPort()); Socket socket = new Socket(); socket.setKeepAlive(false); socket.connect(serverAddress, socketTimeoutMillis); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)); return new SocketPoolable(slot, socket, writer, flushStrategy); }
InetSocketAddress createPeerAddress() { if (remoteAddress == null) { return null; } int port = remotePort > 0 ? remotePort : 0; try { InetAddress address = InetAddress.getByName(remoteAddress); return new InetSocketAddress(address, port); } catch (UnknownHostException e) { return null; } }
LOG.info("connecting to {} {}", host, port); Socket sock; InetSocketAddress hostaddress= host != null ? new InetSocketAddress(host, port) : new InetSocketAddress(InetAddress.getByName(null), port); if (secure) { LOG.info("using secure socket"); sock = new Socket(); sock.connect(hostaddress, timeout); sock.setSoTimeout(timeout); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write(cmd.getBytes()); outstream.flush(); new InputStreamReader(sock.getInputStream())); StringBuilder sb = new StringBuilder(); String line; throw new IOException("Exception while executing four letter word: " + cmd, e); } finally { sock.close(); if (reader != null) { reader.close();
final Socket s = new Socket(); String[] tokens = httpsProxyTunnel.split(":"); LOGGER.log(Level.FINE, "Using HTTP proxy {0}:{1} to connect to CLI port", new Object[]{tokens[0], tokens[1]}); s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1]))); PrintStream o = new PrintStream(s.getOutputStream()); o.print("CONNECT " + clip.endpoint.getHostString() + ":" + clip.endpoint.getPort() + " HTTP/1.0\r\n\r\n"); int ch = s.getInputStream().read(); if (ch<0) throw new IOException("Failed to read the HTTP proxy response: "+rsp); rsp.write(ch); s.close(); LOGGER.log(Level.SEVERE, "Failed to tunnel the CLI port through the HTTP proxy. Falling back to HTTP."); throw new IOException("Failed to establish a connection through HTTP proxy: " + rsp); s.connect(clip.endpoint,3000); out = SocketChannelStream.out(s); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI-connect"); DataInputStream dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI2-connect"); String greeting = dis.readUTF();
@Override public Object run() throws UnknownHostException { final InetSocketAddress resolvedAddress = new InetSocketAddress(InetAddress.getByName(address.getHostName()), address.getPort()); exchange.setSourceAddress(resolvedAddress); return null; } });
@Override OutputStream openNewOutputStream() throws IOException { final Socket socket = socketFactory.createSocket(); // Prevent automatic closing of the connection during periods of inactivity. socket.setKeepAlive(true); // Important not to cache `InetAddress` in case the host moved to a new IP address. socket.connect(new InetSocketAddress(InetAddress.getByName(host), port), connectionTimeoutMs); return new BufferedOutputStream(socket.getOutputStream(), sendBufferSize); } }
public void connect(String hostname, int port, InetAddress localAddr, int localPort) throws IOException { if (hostname == null) { connect(InetAddress.getByName(null), port, localAddr, localPort); } else { this.hostname = hostname; socket = socketFactory.createSocket(); socket.bind(new InetSocketAddress(localAddr, localPort)); socket.connect(new InetSocketAddress(hostname, port), connectTimeout); onConnect(); } }
@Override protected void before() throws Throwable { Socket socket = SocketFactory.getDefault().createSocket(); try { socket.connect(new InetSocketAddress(host, port), Math.toIntExact(timeout.toMillis())); } catch (IOException e) { throw new AssumptionViolatedException( String.format("Couchbase not available on on %s:%d. Skipping tests.", host, port), e); } finally { socket.close(); } } }
@Before public void setUp() throws IOException { Configuration conf = HBaseConfiguration.create(); conf.set(RpcServerFactory.CUSTOM_RPC_SERVER_IMPL_CONF_KEY, rpcServerImpl.getName()); server = RpcServerFactory.createRpcServer(null, "testRpcServer", Lists.newArrayList(new BlockingServiceAndInterface(SERVICE, null)), new InetSocketAddress("localhost", 0), conf, new FifoRpcScheduler(conf, 1)); server.start(); socket = new Socket("localhost", server.getListenerAddress().getPort()); }
private SocketChannel createChannel() throws IOException { final SocketChannel socketChannel = SocketChannel.open(); try { socketChannel.configureBlocking(true); final Socket socket = socketChannel.socket(); socket.setSoTimeout(timeoutMillis); socket.connect(new InetSocketAddress(nodeIdentifier.getLoadBalanceAddress(), nodeIdentifier.getLoadBalancePort())); socket.setSoTimeout(timeoutMillis); return socketChannel; } catch (final Exception e) { try { socketChannel.close(); } catch (final Exception closeException) { e.addSuppressed(closeException); } throw e; } }
@Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { Socket socket = applySettings(createSocket()); socket.bind(new InetSocketAddress(host, localPort)); socket.connect(new InetSocketAddress(host, port), socketTimeout); return socket; }
public static void stat(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("stat".getBytes()).getInt()); s = new Socket(); s.setSoLinger(false, 10); s.setSoTimeout(20000); s.connect(new InetSocketAddress(host, port)); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); os.write(reqBytes); byte[] resBytes = new byte[1024]; int rc = is.read(resBytes); String retv = new String(resBytes); System.out.println("rc=" + rc + " retv=" + retv); } catch (IOException e) { LOG.warn("Unexpected exception", e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } }
public static void main(String[] arg) throws Exception { DatagramServer server = new DatagramServer(null, new InetSocketAddress(0)); server.start(); System.out.println("started"); server.join(); }
@Test public void TestServer() throws Exception { //接受组播和发送组播的数据报服务都要把组播地址添加进来 String host = "239.239.239.88";//多播地址 int port = 9998; InetAddress group = InetAddress.getByName(host); DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET); channel.bind(new InetSocketAddress(port)); channel.join(group, Utils.getLocalNetworkInterface()); ByteBuffer buffer = ByteBuffer.allocate(1024); SocketAddress sender = channel.receive(buffer); buffer.flip(); byte[] data = new byte[buffer.remaining()]; buffer.get(data); System.out.println(new String(data)); }