List of usage examples for java.net InetSocketAddress InetSocketAddress
private InetSocketAddress(int port, String hostname)
From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java
protected void sendTo(int aPort, String anEncodedMessage) { SocketChannel socketChannel = null; try {//from w w w . j ava 2s .c om socketChannel = SocketChannel.open(); InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), aPort); socketChannel.connect(address); socketChannel.write(ByteBuffer.wrap(anEncodedMessage.getBytes())); logger.debug("Sent: {}", anEncodedMessage); } catch (IOException e) { logger.error("Failed to send because: {}: Continuing...", e.getMessage(), e); } finally { if (socketChannel != null) { try { socketChannel.close(); } catch (IOException e) { logger.error("Failed to close client socket because: {}: Continuing...", e.getMessage(), e); } } } }
From source file:net.grinder.util.NetworkUtil.java
private static InetAddress getAddressWithSocket(String byConnecting, int port) { Socket s = null;//from ww w.j a va2 s .c o m try { s = new Socket(); SocketAddress addr = new InetSocketAddress(byConnecting, port); s.connect(addr, 2000); // 2 seconds timeout return s.getLocalAddress(); } catch (Exception e) { return null; } finally { IOUtils.closeQuietly(s); } }
From source file:com.github.aptd.simulation.ui.CHTTPServer.java
/** * ctor// www. j a v a 2 s . c om */ private CHTTPServer() { // web context definition final WebAppContext l_webapp = new WebAppContext(); // server process m_server = new Server(new InetSocketAddress( CConfiguration.INSTANCE.<String>getOrDefault("localhost", "httpserver", "host"), CConfiguration.INSTANCE.<Integer>getOrDefault(8000, "httpserver", "port"))); // set server / webapp connection m_server.setHandler(l_webapp); l_webapp.setServer(m_server); l_webapp.setContextPath("/"); l_webapp.setWelcomeFiles(new String[] { "index.html", "index.htm" }); l_webapp.setResourceBase(CHTTPServer.class .getResource(MessageFormat.format("/{0}/html", CCommon.PACKAGEROOT.replace(".", "/"))) .toExternalForm()); l_webapp.addServlet(new ServletHolder(new ServletContainer(m_restagent)), "/rest/*"); l_webapp.addFilter(new FilterHolder(new CrossOriginFilter()), "/rest/*", EnumSet.of(DispatcherType.REQUEST)); }
From source file:ru.musicplayer.androidclient.network.EasySSLSocketFactory.java
/** * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket, java.lang.String, int, * java.net.InetAddress, int, org.apache.http.params.HttpParams) */// w w w .j a v a 2s. c om public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslSocket = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslSocket.bind(isa); } sslSocket.connect(remoteAddress, connTimeout); sslSocket.setSoTimeout(soTimeout); return sslSocket; }
From source file:com.vmware.photon.controller.common.dcp.helpers.dcp.MultiHostEnvironment.java
public ServerSet getServerSet() { StaticServerSet serverSet = new StaticServerSet(); InetSocketAddress[] servers = new InetSocketAddress[this.hosts.length]; for (int i = 0; i < this.hosts.length; i++) { // Public IP does not work here using local ip servers[i] = new InetSocketAddress("127.0.0.1", this.hosts[i].getPort()); }/*from ww w . j a v a2 s.c o m*/ return new StaticServerSet(servers); }
From source file:edu.cmu.cylab.starslinger.exchange.CheckedSSLSocketFactory.java
@Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params)//from w ww . j a v a2 s.c o m throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); sslsock = limitEnabledCipherSuites(sslsock); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
From source file:be.fedict.eid.idp.sp.protocol.saml2.artifact.ArtifactProxySelector.java
/** * Sets the proxy for a certain location URL. If the proxyHost is null, we * go DIRECT.//from w w w . j a v a 2 s .c o m * * @param location * location * @param proxyHost * proxy hostname * @param proxyPort * proxy port */ public void setProxy(String location, String proxyHost, int proxyPort) { String hostname; try { hostname = new URL(location).getHost(); } catch (MalformedURLException e) { throw new RuntimeException("URL error: " + e.getMessage(), e); } if (null == proxyHost) { LOG.debug("removing proxy for: " + hostname); this.proxies.remove(hostname); } else { LOG.debug("setting proxy for: " + hostname); this.proxies.put(hostname, new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort))); } }
From source file:com.offbynull.portmapper.pcp.PcpController.java
/** * Constructs a {@link PcpController} object. * @param random used to generate nonce values for requests * @param gatewayAddress address of router/gateway * @param selfAddress address of this machine on the interface that can talk to the router/gateway * @param listener a listener to listen for all PCP packets from this router * @throws NullPointerException if any argument is {@code null} * @throws IOException if problems initializing UDP channels *//* w w w.j a va 2 s .c o m*/ public PcpController(Random random, InetAddress gatewayAddress, InetAddress selfAddress, final PcpControllerListener listener) throws IOException { Validate.notNull(random); Validate.notNull(gatewayAddress); Validate.notNull(selfAddress); this.gateway = new InetSocketAddress(gatewayAddress, 5351); List<DatagramChannel> channels = new ArrayList<>(3); try { unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(0)); ipv4MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET); ipv4MulticastChannel.configureBlocking(false); ipv4MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); ipv4MulticastChannel.socket().bind(new InetSocketAddress(5350)); NetworkUtils.multicastListenOnAllIpv4InterfaceAddresses(ipv4MulticastChannel); ipv6MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET6); ipv6MulticastChannel.configureBlocking(false); ipv6MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); ipv6MulticastChannel.socket().bind(new InetSocketAddress(5350)); NetworkUtils.multicastListenOnAllIpv6InterfaceAddresses(ipv6MulticastChannel); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); IOUtils.closeQuietly(ipv4MulticastChannel); IOUtils.closeQuietly(ipv6MulticastChannel); throw ioe; } channels.add(unicastChannel); channels.add(ipv4MulticastChannel); channels.add(ipv6MulticastChannel); this.communicator = new UdpCommunicator(channels); this.selfAddress = selfAddress; this.random = random; this.communicator.startAsync().awaitRunning(); if (listener != null) { this.communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { CommunicationType type; if (channel == unicastChannel) { type = CommunicationType.UNICAST; } else if (channel == ipv4MulticastChannel || channel == ipv6MulticastChannel) { type = CommunicationType.MULTICAST; } else { return; // unknown, do nothing } try { packet.mark(); listener.incomingResponse(type, new AnnouncePcpResponse(packet)); } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD // ignore } finally { packet.reset(); } try { packet.mark(); listener.incomingResponse(type, new MapPcpResponse(packet)); } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD // ignore } finally { packet.reset(); } try { packet.mark(); listener.incomingResponse(type, new PeerPcpResponse(packet)); } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD // ignore } finally { packet.reset(); } } }); } }
From source file:com.ipservices.alarmcallback.victorops.VictorOpsClient.java
public void sendAlert(Stream stream, final AlertCondition.CheckResult checkResult, final String entityId) throws AlarmCallbackException { final HttpURLConnection conn; try {/*w w w . java2 s. co m*/ if (proxyUri != null) { final InetSocketAddress proxyAddress = new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort()); final Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress); conn = (HttpURLConnection) apiUrl.openConnection(proxy); } else { conn = (HttpURLConnection) apiUrl.openConnection(); } conn.setRequestMethod("POST"); } catch (IOException e) { throw new AlarmCallbackException("Error while opening connection to VictorOps API.", e); } conn.setDoOutput(true); try (final OutputStream requestStream = conn.getOutputStream()) { final VictorOpsAlert alert = new VictorOpsAlert(messageType, baseUrl); alert.build(stream, checkResult, entityId); requestStream.write(objectMapper.writeValueAsBytes(alert)); requestStream.flush(); final InputStream responseStream; if (conn.getResponseCode() == 200) { responseStream = conn.getInputStream(); } else { LOG.warn("Received response {} from server.", conn.getResponseCode()); responseStream = conn.getErrorStream(); } final VictorOpsAlertReply reply = objectMapper.readValue(responseStream, VictorOpsAlertReply.class); if ("success".equals(reply.result)) { LOG.debug("Successfully sent alert to VictorOps with entity id {}", reply.entityId); } else { LOG.warn("Error while creating VictorOps alert: {}", reply.message); throw new AlarmCallbackException("Error while creating VictorOps event: " + reply.message); } } catch (IOException e) { throw new AlarmCallbackException("Could not POST alert notification to VictorOps API.", e); } }
From source file:org.hydracache.server.httpd.AsyncHttpLightServer.java
InetSocketAddress buildInetSocketAddress() { InetSocketAddress address = null; address = new InetSocketAddress(ip, portNumber); if (log.isDebugEnabled()) { log.debug("Server is listening on address [" + address.getAddress().getHostAddress() + ":" + address.getPort() + "]"); }/*from w w w . j av a 2 s . c o m*/ return address; }