List of usage examples for java.net Socket getInetAddress
public InetAddress getInetAddress()
From source file:net.sbbi.upnp.ServicesEventing.java
/** * Register state variable events notification for a device service * @param service the service to register with * @param handler the registrant object/* ww w .j av a2s .com*/ * @param subscriptionDuration subscription time in seconds, -1 for infinite time * @return an ServiceEventSubscription object instance containing all the required info or null if no subscription done * @throws IOException if some IOException error happens during coms with the device */ public ServiceEventSubscription registerEvent(UPNPService service, ServiceEventHandler handler, int subscriptionDuration) throws IOException { URL eventingLoc = service.getEventSubURL(); if (eventingLoc != null) { if (!inService) startServicesEventingThread(); String duration = Integer.toString(subscriptionDuration); if (subscriptionDuration == -1) { duration = "infinite"; } Subscription sub = lookupSubscriber(service, handler); if (sub != null) { // allready registered let's try to unregister it unRegister(service, handler); } StringBuffer packet = new StringBuffer(64); packet.append("SUBSCRIBE ").append(eventingLoc.getFile()).append(" HTTP/1.1\r\n"); packet.append("HOST: ").append(eventingLoc.getHost()).append(":").append(eventingLoc.getPort()) .append("\r\n"); packet.append("CALLBACK: <http://").append(InetAddress.getLocalHost().getHostAddress()).append(":") .append(daemonPort).append("").append(eventingLoc.getFile()).append(">\r\n"); packet.append("NT: upnp:event\r\n"); packet.append("Connection: close\r\n"); packet.append("TIMEOUT: Second-").append(duration).append("\r\n\r\n"); Socket skt = new Socket(eventingLoc.getHost(), eventingLoc.getPort()); skt.setSoTimeout(30000); // 30 secs timeout according to the specs if (log.isDebugEnabled()) log.debug(packet); OutputStream out = skt.getOutputStream(); out.write(packet.toString().getBytes()); out.flush(); InputStream in = skt.getInputStream(); StringBuffer data = new StringBuffer(); int readen = 0; byte[] buffer = new byte[256]; while ((readen = in.read(buffer)) != -1) { data.append(new String(buffer, 0, readen)); } in.close(); out.close(); skt.close(); if (log.isDebugEnabled()) log.debug(data.toString()); if (data.toString().trim().length() > 0) { HttpResponse resp = new HttpResponse(data.toString()); if (resp.getHeader().startsWith("HTTP/1.1 200 OK")) { String sid = resp.getHTTPHeaderField("SID"); String actualTimeout = resp.getHTTPHeaderField("TIMEOUT"); int durationTime = 0; // actualTimeout = Second-xxx or Second-infinite if (!actualTimeout.equalsIgnoreCase("Second-infinite")) { durationTime = Integer.parseInt(actualTimeout.substring(7)); } sub = new Subscription(); sub.handler = handler; sub.sub = new ServiceEventSubscription(service.getServiceType(), service.getServiceId(), service.getEventSubURL(), sid, skt.getInetAddress(), durationTime); synchronized (registered) { registered.add(sub); } return sub.sub; } } } return null; }
From source file:org.apache.geode.internal.net.SocketCreator.java
/** * Will be a server socket... this one simply registers the listeners. *//*from ww w.j a v a2 s . co m*/ public void configureServerSSLSocket(Socket socket) throws IOException { if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; try { sslSocket.startHandshake(); SSLSession session = sslSocket.getSession(); Certificate[] peer = session.getPeerCertificates(); if (logger.isDebugEnabled()) { logger.debug(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0, ((X509Certificate) peer[0]).getSubjectDN())); } } catch (SSLPeerUnverifiedException ex) { if (this.sslConfig.isRequireAuth()) { logger.fatal( LocalizedMessage.create( LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER_0_1, new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }), ex); throw ex; } } catch (SSLException ex) { logger.fatal( LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1, new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }), ex); throw ex; } } }
From source file:NanoHTTPD.java
/** * Start the server./*w ww.ja v a 2 s . c o m*/ * * @throws IOException if the socket is in use. */ public void start() throws IOException { myServerSocket = new ServerSocket(); myServerSocket .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); myThread = new Thread(new Runnable() { @Override public void run() { do { try { final Socket finalAccept = myServerSocket.accept(); registerConnection(finalAccept); finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); final InputStream inputStream = finalAccept.getInputStream(); asyncRunner.exec(new Runnable() { @Override public void run() { OutputStream outputStream = null; try { outputStream = finalAccept.getOutputStream(); TempFileManager tempFileManager = tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress()); while (!finalAccept.isClosed()) { session.execute(); } } catch (Exception e) { // When the socket is closed by the client, we throw our own SocketException // to break the "keep alive" loop above. if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { e.printStackTrace(); } } finally { safeClose(outputStream); safeClose(inputStream); safeClose(finalAccept); unRegisterConnection(finalAccept); } } }); } catch (IOException e) { } } while (!myServerSocket.isClosed()); } }); myThread.setDaemon(true); myThread.setName("NanoHttpd Main Listener"); myThread.start(); }
From source file:org.apache.nutch.protocol.ftp.Client.java
/** * open a passive data connection socket * /*from w w w . ja v a 2s . co m*/ * @param command * @param arg * @return * @throws IOException * @throws FtpExceptionCanNotHaveDataConnection */ protected Socket __openPassiveDataConnection(int command, String arg) throws IOException, FtpExceptionCanNotHaveDataConnection { Socket socket; // // 20040317, xing, accommodate ill-behaved servers, see below // int port_previous = __passivePort; if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) throw new FtpExceptionCanNotHaveDataConnection("pasv() failed. " + getReplyString()); try { __parsePassiveModeReply(getReplyStrings()[0]); } catch (MalformedServerReplyException e) { throw new FtpExceptionCanNotHaveDataConnection(e.getMessage()); } // // 20040317, xing, accommodate ill-behaved servers, see above // int count = 0; // System.err.println("__passivePort "+__passivePort); // System.err.println("port_previous "+port_previous); // while (__passivePort == port_previous) { // // just quit if too many tries. make it an exception here? // if (count++ > 10) // return null; // // slow down further for each new try // Thread.sleep(500*count); // if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) // throw new FtpExceptionCanNotHaveDataConnection( // "pasv() failed. " + getReplyString()); // //return null; // try { // __parsePassiveModeReply(getReplyStrings()[0]); // } catch (MalformedServerReplyException e) { // throw new FtpExceptionCanNotHaveDataConnection(e.getMessage()); // } // } socket = _socketFactory_.createSocket(__passiveHost, __passivePort); if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { socket.close(); return null; } if (__remoteVerificationEnabled && !verifyRemote(socket)) { InetAddress host1, host2; host1 = socket.getInetAddress(); host2 = getRemoteAddress(); socket.close(); // our precaution throw new FtpExceptionCanNotHaveDataConnection( "Host attempting data connection " + host1.getHostAddress() + " is not same as server " + host2.getHostAddress() + " So we intentionally close it for security precaution."); } if (__dataTimeout >= 0) socket.setSoTimeout(__dataTimeout); return socket; }
From source file:org.apache.hadoop.hdfs.server.datanode.DWRRDataXceiver.java
@Override public void replaceBlock(final ExtendedBlock block, final Token<BlockTokenIdentifier> blockToken, final String delHint, final DatanodeInfo proxySource) throws IOException { updateCurrentThreadName("Replacing block " + block + " from " + delHint); /* read header */ block.setNumBytes(DataXceiverServer.estimateBlockSize); if (datanode.isBlockTokenEnabled) { try {/*www . java 2 s . c o m*/ datanode.blockPoolTokenSecretManager.checkAccess(blockToken, null, block, BlockTokenSecretManager.AccessMode.REPLACE); } catch (InvalidToken e) { LOG.warn("Invalid access token in request from " + remoteAddress + " for OP_REPLACE_BLOCK for block " + block + " : " + e.getLocalizedMessage()); sendResponse(ERROR_ACCESS_TOKEN, "Invalid access token"); return; } } if (!DataXceiverServer.balanceThrottler.acquire()) { // not able to start String msg = "Not able to receive block " + block.getBlockId() + " from " + peer.getRemoteAddressString() + " because threads " + "quota is exceeded."; LOG.warn(msg); sendResponse(ERROR, msg); return; } Socket proxySock = null; DataOutputStream proxyOut = null; Status opStatus = SUCCESS; String errMsg = null; BlockReceiver blockReceiver = null; DataInputStream proxyReply = null; try { // get the output stream to the proxy final String dnAddr = proxySource.getXferAddr(connectToDnViaHostname); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to datanode " + dnAddr); } InetSocketAddress proxyAddr = NetUtils.createSocketAddr(dnAddr); proxySock = datanode.newSocket(); NetUtils.connect(proxySock, proxyAddr, dnConf.socketTimeout); proxySock.setSoTimeout(dnConf.socketTimeout); OutputStream unbufProxyOut = NetUtils.getOutputStream(proxySock, dnConf.socketWriteTimeout); InputStream unbufProxyIn = NetUtils.getInputStream(proxySock); if (dnConf.encryptDataTransfer && !dnConf.trustedChannelResolver.isTrusted(proxySock.getInetAddress())) { IOStreamPair encryptedStreams = DataTransferEncryptor.getEncryptedStreams(unbufProxyOut, unbufProxyIn, datanode.blockPoolTokenSecretManager.generateDataEncryptionKey(block.getBlockPoolId())); unbufProxyOut = encryptedStreams.out; unbufProxyIn = encryptedStreams.in; } proxyOut = new DataOutputStream( new BufferedOutputStream(unbufProxyOut, HdfsConstants.SMALL_BUFFER_SIZE)); proxyReply = new DataInputStream( new BufferedInputStream(unbufProxyIn, HdfsConstants.IO_FILE_BUFFER_SIZE)); /* send request to the proxy */ new Sender(proxyOut).copyBlock(block, blockToken); // receive the response from the proxy BlockOpResponseProto copyResponse = BlockOpResponseProto.parseFrom(PBHelper.vintPrefixed(proxyReply)); if (copyResponse.getStatus() != SUCCESS) { if (copyResponse.getStatus() == ERROR_ACCESS_TOKEN) { throw new IOException("Copy block " + block + " from " + proxySock.getRemoteSocketAddress() + " failed due to access token error"); } throw new IOException( "Copy block " + block + " from " + proxySock.getRemoteSocketAddress() + " failed"); } // get checksum info about the block we're copying ReadOpChecksumInfoProto checksumInfo = copyResponse.getReadOpChecksumInfo(); DataChecksum remoteChecksum = DataTransferProtoUtil.fromProto(checksumInfo.getChecksum()); // open a block receiver and check if the block does not exist blockReceiver = new BlockReceiver(block, proxyReply, proxySock.getRemoteSocketAddress().toString(), proxySock.getLocalSocketAddress().toString(), null, 0, 0, 0, "", null, datanode, remoteChecksum, CachingStrategy.newDropBehind()); // receive a block blockReceiver.receiveBlock(null, null, null, null, DataXceiverServer.balanceThrottler, null); // notify name node datanode.notifyNamenodeReceivedBlock(block, delHint, blockReceiver.getStorageUuid()); LOG.info("Moved " + block + " from " + peer.getRemoteAddressString() + ", delHint=" + delHint); } catch (IOException ioe) { opStatus = ERROR; errMsg = "opReplaceBlock " + block + " received exception " + ioe; LOG.info(errMsg); throw ioe; } finally { // receive the last byte that indicates the proxy released its thread resource if (opStatus == SUCCESS) { try { proxyReply.readChar(); } catch (IOException ignored) { } } // now release the thread resource DataXceiverServer.balanceThrottler.release(); // send response back try { sendResponse(opStatus, errMsg); } catch (IOException ioe) { LOG.warn("Error writing reply back to " + peer.getRemoteAddressString()); } IOUtils.closeStream(proxyOut); IOUtils.closeStream(blockReceiver); IOUtils.closeStream(proxyReply); } //update metrics datanode.metrics.addReplaceBlockOp(elapsed()); }
From source file:org.apache.hadoop.dfs.DataNode.java
private static void receiveResponse(Socket s, int numTargets) throws IOException { // check the response DataInputStream reply = new DataInputStream( new BufferedInputStream(NetUtils.getInputStream(s), BUFFER_SIZE)); try {/*from w w w. j a v a 2s . c om*/ for (int i = 0; i < numTargets; i++) { short opStatus = reply.readShort(); if (opStatus != OP_STATUS_SUCCESS) { throw new IOException("operation failed at " + s.getInetAddress()); } } } finally { IOUtils.closeStream(reply); } }
From source file:org.lockss.protocol.BlockingStreamComm.java
void processIncomingConnection(Socket sock) throws IOException { if (sock.isClosed()) { // This should no longer happen throw new SocketException("processIncomingConnection got closed socket"); }//from ww w. java2 s.c o m // Setup socket (SO_TIMEOUT, etc.) before SSL handshake setupOpenSocket(sock); log.debug2("Accepted connection from " + new IPAddr(sock.getInetAddress())); // SSL handshake now performed by channel BlockingPeerChannel chan = getSocketFactory().newPeerChannel(this, sock); chan.startIncoming(); }
From source file:fi.iki.elonen.NanoHTTPD.java
/** * Start the server./*from ww w . j a v a 2 s . c om*/ * * @throws IOException if the socket is in use. */ public void start() throws IOException { myServerSocket = new ServerSocket(); myServerSocket .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); myThread = new Thread(new Runnable() { @Override public void run() { do { try { final Socket finalAccept = myServerSocket.accept(); registerConnection(finalAccept); finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); final InputStream inputStream = finalAccept.getInputStream(); if (inputStream == null) { safeClose(finalAccept); unRegisterConnection(finalAccept); } else { asyncRunner.exec(new Runnable() { @Override public void run() { BufferedInputStream bufferedInputStream = null; OutputStream outputStream = null; try { bufferedInputStream = new BufferedInputStream(inputStream); outputStream = finalAccept.getOutputStream(); TempFileManager tempFileManager = tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(tempFileManager, bufferedInputStream, outputStream, finalAccept.getInetAddress()); while (!finalAccept.isClosed()) { session.execute(); } } catch (Exception e) { // When the socket is closed by the client, we throw our own SocketException // to break the "keep alive" loop above. if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { e.printStackTrace(); } } finally { safeClose(bufferedInputStream); safeClose(outputStream); safeClose(finalAccept); unRegisterConnection(finalAccept); } } }); } } catch (IOException e) { } } while (!myServerSocket.isClosed()); } }); myThread.setDaemon(true); myThread.setName("NanoHttpd Main Listener"); myThread.start(); }
From source file:org.apache.geode.internal.net.SocketCreator.java
/** * When a socket is accepted from a server socket, it should be passed to this method for SSL * configuration./*from w w w. j a va 2s. c o m*/ */ private void configureClientSSLSocket(Socket socket, int timeout) throws IOException { if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; sslSocket.setUseClientMode(true); sslSocket.setEnableSessionCreation(true); String[] protocols = this.sslConfig.getProtocolsAsStringArray(); // restrict cyphers if (protocols != null && !"any".equalsIgnoreCase(protocols[0])) { sslSocket.setEnabledProtocols(protocols); } String[] ciphers = this.sslConfig.getCiphersAsStringArray(); if (ciphers != null && !"any".equalsIgnoreCase(ciphers[0])) { sslSocket.setEnabledCipherSuites(ciphers); } try { if (timeout > 0) { sslSocket.setSoTimeout(timeout); } sslSocket.startHandshake(); SSLSession session = sslSocket.getSession(); Certificate[] peer = session.getPeerCertificates(); if (logger.isDebugEnabled()) { logger.debug(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0, ((X509Certificate) peer[0]).getSubjectDN())); } } catch (SSLHandshakeException ex) { logger.fatal( LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1, new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }), ex); throw ex; } catch (SSLPeerUnverifiedException ex) { if (this.sslConfig.isRequireAuth()) { logger.fatal(LocalizedMessage .create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER), ex); throw ex; } } catch (SSLException ex) { logger.fatal( LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1, new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }), ex); throw ex; } } }
From source file:com.l2jfree.gameserver.status.GameStatusThread.java
private boolean setEnchant(Socket gm, L2Player activeChar, int ench, int armorType) { // now we need to find the equipped weapon of the targeted character... int curEnchant = 0; // display purposes only L2ItemInstance itemInstance = null;/*from w w w.ja v a 2 s. c om*/ // only attempt to enchant if there is a weapon equipped L2ItemInstance parmorInstance = activeChar.getInventory().getPaperdollItem(armorType); if (parmorInstance != null && parmorInstance.getLocationSlot() == armorType) { itemInstance = parmorInstance; } else { // for bows/crossbows and double handed weapons parmorInstance = activeChar.getInventory().getPaperdollItem(Inventory.PAPERDOLL_LRHAND); if (parmorInstance != null && parmorInstance.getLocationSlot() == Inventory.PAPERDOLL_LRHAND) itemInstance = parmorInstance; } if (itemInstance != null) { curEnchant = itemInstance.getEnchantLevel(); // set enchant value activeChar.getInventory().unEquipItemInSlotAndRecord(armorType); itemInstance.setEnchantLevel(ench); activeChar.getInventory().equipItemAndRecord(itemInstance); // send packets InventoryUpdate iu = new InventoryUpdate(); iu.addModifiedItem(itemInstance); activeChar.sendPacket(iu); activeChar.broadcastUserInfo(); // informations activeChar.sendMessage("Changed enchantment of " + activeChar.getName() + "'s " + itemInstance.getItem().getName() + " from " + curEnchant + " to " + ench + "."); activeChar.sendMessage("Admin has changed the enchantment of your " + itemInstance.getItem().getName() + " from " + curEnchant + " to " + ench + "."); String IP = gm.getInetAddress().getHostAddress(); // log GMAudit.auditGMAction(IP, activeChar.getName(), "telnet-enchant", "telnet-enchant", itemInstance.getItem().getName() + "(" + itemInstance.getObjectId() + ")" + " from " + curEnchant + " to " + ench); return true; } return false; }