private boolean connectSPPMon() { if (state == ConnectionEvent.CONNECTION_PENDING) { ExpCoordinator.print( new String("NCCPConnection(" + host + ", " + port + ").connect connection pending"), 0); while (state == ConnectionEvent.CONNECTION_PENDING) { try { Thread.sleep(500); } catch (java.lang.InterruptedException e) { } } return (isConnected()); } state = ConnectionEvent.CONNECTION_PENDING; if (nonProxy != null) { try { nonProxy.connect(); } catch (UnknownHostException e) { boolean rtn = informUserError("Don't know about host: " + host + ":" + e.getMessage()); return rtn; } catch (SocketTimeoutException e) { boolean rtn = informUserError("Socket time out for " + host + ":" + e.getMessage()); return rtn; } catch (IOException e) { boolean rtn = informUserError("Couldnt get I/O for " + host + ":" + e.getMessage()); return rtn; } } return (isConnected()); }
// 获得IP地址 public static String getIpAddr(HttpServletRequest request) { String ipAddress = null; ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals("127.0.0.1")) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } return ipAddress; }
public Process(String name, int pid, int n) { this.name = name; this.port = Utils.REGISTRAR_PORT + pid; this.host = "UNKNOWN"; try { this.host = (InetAddress.getLocalHost()).getHostName(); } catch (UnknownHostException e) { String msg = String.format("Error: getHostName() failed at %s.", this.getInfo()); System.err.println(msg); System.err.println(e.getMessage()); System.exit(1); } this.pid = pid; this.n = n; random = new Random(); /* Accepts connections from one of Registrar's worker threads */ new Thread(new Listener(this)).start(); /* Connect to registrar */ socket = connect(); init(); Utils.out(pid, "Connected."); }
/** * Creates a new, empty SessionDescription. The session is set as follows: * * <p>v=0 * * <p>o=this.createOrigin ("user", InetAddress.getLocalHost().toString()); * * <p>s=- * * <p>t=0 0 * * @throws SdpException SdpException, - if there is a problem constructing the SessionDescription. * @return a new, empty SessionDescription. */ public SessionDescription createSessionDescription() throws SdpException { SessionDescriptionImpl sessionDescriptionImpl = new SessionDescriptionImpl(); ProtoVersionField ProtoVersionField = new ProtoVersionField(); ProtoVersionField.setVersion(0); sessionDescriptionImpl.setVersion(ProtoVersionField); OriginField originImpl = null; try { originImpl = (OriginField) this.createOrigin("user", InetAddress.getLocalHost().getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } sessionDescriptionImpl.setOrigin(originImpl); SessionNameField sessionNameImpl = new SessionNameField(); sessionNameImpl.setValue("-"); sessionDescriptionImpl.setSessionName(sessionNameImpl); TimeDescriptionImpl timeDescriptionImpl = new TimeDescriptionImpl(); TimeField timeImpl = new TimeField(); timeImpl.setZero(); timeDescriptionImpl.setTime(timeImpl); Vector times = new Vector(); times.addElement(timeDescriptionImpl); sessionDescriptionImpl.setTimeDescriptions(times); sessionDescriptionsList.addElement(sessionDescriptionImpl); return sessionDescriptionImpl; }
private Descrittore contatta_server(String nome) { // variabili per l'RMI RMIServerInt serv = null; // server Descrittore descr_rit = null; // descrittore ritornato if (nome == null) { System.out.println("## contatta_server di Download ha ricevuto parametro null ! "); return null; } System.out.println("@ provo a contattare il server RMI "); // ################ RMI ################ if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } Object o = null; try { // o = Naming.lookup("rmi://192.168.0.10:1099/srmi"); Registry registry = LocateRegistry.getRegistry(server.getHostAddress()); o = registry.lookup("srmi"); } catch (RemoteException e) { System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome); e.printStackTrace(); } catch (NotBoundException e) { System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome); e.printStackTrace(); } if (o == null) { System.out.println( "## l'RMI di Download - contatta_server di " + nome + " ha ritornato l'oggetto o null"); return null; } serv = (RMIServerInt) o; try { descr_rit = serv.lookup(nome, InetAddress.getLocalHost()); } catch (RemoteException e) { e.printStackTrace(); System.out.println("## Problemi con Lookup di " + nome); return null; } catch (UnknownHostException e) { e.printStackTrace(); System.out.println("## Problemi con Lookup di " + nome); return null; } return descr_rit; }
public void Connect() { try { System.out.println("ok"); socket99 = new Socket(serverIP, 9999); socket66 = new Socket(serverIP, 6666); socket88 = new Socket(serverIP, 8888); isConnected = true; } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
String getLocalIPAddr() { if (localAddr == null) { try { IPAddr localHost = IPAddr.getLocalHost(); localAddr = localHost.getHostAddress(); } catch (UnknownHostException e) { // shouldn't happen log.error("LockssServlet: getLocalHost: " + e.toString()); return "???"; } } return localAddr; }
/** @return true if the request was served. */ private boolean proxyRemotePath( HttpServletRequest req, HttpServletResponse resp, URI remoteURI, boolean failEarlyOn404) throws IOException, ServletException, UnknownHostException { try { return proxyRemoteUrl(req, resp, new URL(remoteURI.toString()), failEarlyOn404); } catch (MalformedURLException e) { String message = NLS.bind("Malformed remote URL: {0}", remoteURI.toString()); handleException( resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, message, e)); } catch (UnknownHostException e) { String message = NLS.bind("Unknown host {0}", e.getMessage()); handleException( resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, message, e)); } catch (Exception e) { String message = NLS.bind("An error occurred while retrieving {0}", remoteURI.toString()); handleException( resp, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message, e)); } return true; }
public static void main(String[] args) throws EOFException { queue = new ArrayList<Traffic>(); ObjectInputStream OISforTG = null; ObjectOutputStream OOSforLot = null; System.out.print("login?"); sc = new Scanner(System.in); String input = sc.nextLine(); if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) { // System.out.println(ConnectionData.ipTG+" "+ConnectionData.portForTG); try { // socketForManager = new Socket(ConnectionData.ipMani, ConnectionData.portForManager); socketForTG = new Socket(ConnectionData.ipTG, ConnectionData.portForTG); socketForTime = new Socket(ConnectionData.ipTG, ConnectionData.portForTime); socketForParkingLot = new Socket(ConnectionData.ipLot, ConnectionData.portForLot); System.out.println("Connected"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } receiverForManager RFM = new receiverForManager(); Thread ThreadRFM = new Thread(RFM); ThreadRFM.start(); trafficReceiver trafficRec = new trafficReceiver(); Thread ThreadTraffic = new Thread(trafficRec); ThreadTraffic.start(); try { OOSforLot = new ObjectOutputStream(socketForParkingLot.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException npe) { npe.printStackTrace(); } timeReader TR = new timeReader(); Thread thread = new Thread(TR); thread.start(); carReturned CR = new carReturned(); Thread thread1 = new Thread(CR); thread1.start(); // System.out.println("reach1"); while (true) { try { if (Token > 0 && queue.size() > 0) { Token--; System.out.println(Token); OOSforLot.writeObject(queue.get(0)); } else if (Token == 0 && queue.size() > 0) { String carOrig = queue.get(0).getGeneratedTime(); Integer carOrigInt[] = utils.timeConverter(carOrig); int Orig = (carOrigInt[0] * 3600) + (carOrigInt[1] * 60); int Curren = (currentTime[0] * 3600) + (currentTime[1] * 60); if ((Curren - Orig) > 600) { // need to something... // // // // } else { System.out.println("Token: " + Token + " queue Size: " + queue.size()); continue; } } } catch (IOException e) { e.printStackTrace(); } } } }
/** * connect: connect to the master * * @return: true for success and false for failure */ protected boolean connect() { boolean connected = true; try { _sock = new Socket(_serverIP, _serverPort); _out = new PrintWriter(_sock.getOutputStream(), true); _in = new BufferedReader(new InputStreamReader(_sock.getInputStream())); String reply = sendAll(); if (!reply.equals(ProtocolConstants.PACK_STR_CONFIRM_HEAD)) { /* Tokenize */ StringTokenizer st = new StringTokenizer(reply); if (st.nextToken().equals(ProtocolConstants.PACK_STR_ERRMES_HEAD)) { _elog(st.nextToken()); return false; } } _userSock = new Socket(_serverIP, _serverPort); _userOut = new PrintWriter(_userSock.getOutputStream(), true); _userIn = new BufferedReader(new InputStreamReader(_userSock.getInputStream())); String replyUser = sendUserID(); if (!replyUser.equals(ProtocolConstants.PACK_STR_CONFIRM_HEAD)) { throw new Exception("Not confirmed"); } } catch (UnknownHostException e) { if (!_server.noException()) { _elog(e.toString()); } if (_server.debugMode()) { e.printStackTrace(); } connected = false; } catch (IOException e) { if (!_server.noException()) { _elog(e.toString()); } if (_server.debugMode()) { e.printStackTrace(); } connected = false; } catch (Exception e) { if (!_server.noException()) { _elog(e.toString()); } if (_server.debugMode()) { e.printStackTrace(); } connected = false; } if (!connected) { return connected; } if (!connected) { /* Remove the pair of socket */ _sock = null; _in = null; _out = null; _userSock = null; _userOut = null; _userIn = null; } return connected; }
public static LoaderOptions parseArgs(String cmdArgs[]) { CommandLineParser parser = new GnuParser(); CmdLineOptions options = getCmdLineOptions(); try { CommandLine cmd = parser.parse(options, cmdArgs, false); if (cmd.hasOption(HELP_OPTION)) { printUsage(options); System.exit(0); } String[] args = cmd.getArgs(); if (args.length == 0) { System.err.println("Missing sstable directory argument"); printUsage(options); System.exit(1); } if (args.length > 1) { System.err.println("Too many arguments"); printUsage(options); System.exit(1); } String dirname = args[0]; File dir = new File(dirname); if (!dir.exists()) errorMsg("Unknown directory: " + dirname, options); if (!dir.isDirectory()) errorMsg(dirname + " is not a directory", options); LoaderOptions opts = new LoaderOptions(dir); opts.debug = cmd.hasOption(DEBUG_OPTION); opts.verbose = cmd.hasOption(VERBOSE_OPTION); opts.noProgress = cmd.hasOption(NOPROGRESS_OPTION); if (cmd.hasOption(RPC_PORT_OPTION)) opts.rpcPort = Integer.parseInt(cmd.getOptionValue(RPC_PORT_OPTION)); if (cmd.hasOption(USER_OPTION)) opts.user = cmd.getOptionValue(USER_OPTION); if (cmd.hasOption(PASSWD_OPTION)) opts.passwd = cmd.getOptionValue(PASSWD_OPTION); if (cmd.hasOption(INITIAL_HOST_ADDRESS_OPTION)) { String[] nodes = cmd.getOptionValue(INITIAL_HOST_ADDRESS_OPTION).split(","); try { for (String node : nodes) { opts.hosts.add(InetAddress.getByName(node.trim())); } } catch (UnknownHostException e) { errorMsg("Unknown host: " + e.getMessage(), options); } } else { System.err.println("Initial hosts must be specified (-d)"); printUsage(options); System.exit(1); } if (cmd.hasOption(IGNORE_NODES_OPTION)) { String[] nodes = cmd.getOptionValue(IGNORE_NODES_OPTION).split(","); try { for (String node : nodes) { opts.ignores.add(InetAddress.getByName(node.trim())); } } catch (UnknownHostException e) { errorMsg("Unknown host: " + e.getMessage(), options); } } // try to load config file first, so that values can be rewritten with other option values. // otherwise use default config. Config config; if (cmd.hasOption(CONFIG_PATH)) { File configFile = new File(cmd.getOptionValue(CONFIG_PATH)); if (!configFile.exists()) { errorMsg("Config file not found", options); } config = new YamlConfigurationLoader().loadConfig(configFile.toURI().toURL()); } else { config = new Config(); } opts.storagePort = config.storage_port; opts.sslStoragePort = config.ssl_storage_port; opts.throttle = config.stream_throughput_outbound_megabits_per_sec; opts.encOptions = config.client_encryption_options; opts.serverEncOptions = config.server_encryption_options; if (cmd.hasOption(THROTTLE_MBITS)) { opts.throttle = Integer.parseInt(cmd.getOptionValue(THROTTLE_MBITS)); } if (cmd.hasOption(SSL_TRUSTSTORE)) { opts.encOptions.truststore = cmd.getOptionValue(SSL_TRUSTSTORE); } if (cmd.hasOption(SSL_TRUSTSTORE_PW)) { opts.encOptions.truststore_password = cmd.getOptionValue(SSL_TRUSTSTORE_PW); } if (cmd.hasOption(SSL_KEYSTORE)) { opts.encOptions.keystore = cmd.getOptionValue(SSL_KEYSTORE); // if a keystore was provided, lets assume we'll need to use it opts.encOptions.require_client_auth = true; } if (cmd.hasOption(SSL_KEYSTORE_PW)) { opts.encOptions.keystore_password = cmd.getOptionValue(SSL_KEYSTORE_PW); } if (cmd.hasOption(SSL_PROTOCOL)) { opts.encOptions.protocol = cmd.getOptionValue(SSL_PROTOCOL); } if (cmd.hasOption(SSL_ALGORITHM)) { opts.encOptions.algorithm = cmd.getOptionValue(SSL_ALGORITHM); } if (cmd.hasOption(SSL_STORE_TYPE)) { opts.encOptions.store_type = cmd.getOptionValue(SSL_STORE_TYPE); } if (cmd.hasOption(SSL_CIPHER_SUITES)) { opts.encOptions.cipher_suites = cmd.getOptionValue(SSL_CIPHER_SUITES).split(","); } if (cmd.hasOption(TRANSPORT_FACTORY)) { ITransportFactory transportFactory = getTransportFactory(cmd.getOptionValue(TRANSPORT_FACTORY)); configureTransportFactory(transportFactory, opts); opts.transportFactory = transportFactory; } return opts; } catch (ParseException | ConfigurationException | MalformedURLException e) { errorMsg(e.getMessage(), options); return null; } }
private ArrayList<InetAddress> contatta_Tracker(Descrittore descr) { InetAddress server = null; ObjectInputStream data_in; ObjectOutputStream data_out; InputStream in; OutputStream out; ArrayList<InetAddress> lista = null; /* socket per la comunicazione TCP */ SSLSocketFactory factory = null; SSLSocket socket = null; // ###### preparo l'indirizzo try { server = InetAddress.getByName("192.168.0.10"); } catch (UnknownHostException e1) { e1.printStackTrace(); } // ###### creo il socket if (descr == null) { System.out.println("## contatta_tracker di Download ha ricevuto parametro null ! "); return null; } System.out.println( "@ provo a contattare via TCP il Tracker a " + server.toString() + " porta " + descr.getTcp()); try { factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); socket = (SSLSocket) factory.createSocket(server, descr.getTcp()); } catch (IOException e1) { System.out.println("# eccezione nella creazione socket verso il Tracker TCP"); e1.printStackTrace(); } System.out.println("@ socket creato "); if (factory == null || socket == null) { System.out.println("## la connessione ssl di Download ha ritornato null ! "); return null; } try { System.out.println("@ out_stream "); out = socket.getOutputStream(); System.out.println("@ out "); data_out = new ObjectOutputStream(out); System.out.println("@ in_stream "); in = socket.getInputStream(); System.out.println("@ in "); data_in = new ObjectInputStream(in); System.out.println("@ Downloader: streams ok "); data_out.writeObject(descr); // TODO Perchè ? data_out.flush(); System.out.println("@ descrittore mandato "); lista = (ArrayList<InetAddress>) data_in.readObject(); if (lista == null) System.out.println( "@ ritornata lista vuota dal tracker riguardo : " + descr.nome); // TODO sarebbe un caso plausibile else System.out.println("@ lista ricevuta : " + lista.toString()); } catch (IOException e) { System.out.println("# eccezione I/O nella creazione socket verso il Tracker TCP"); e.printStackTrace(); } catch (ClassNotFoundException e) { System.out.println("# eccezione C N F nella creazione socket verso il Tracker TCP"); e.printStackTrace(); } return lista; }
protected Map getVersionCheckInfoSupport( String reason, boolean only_if_cached, boolean force, boolean v6) { try { synchronized (listeners) { if (REASON_UPDATE_CHECK_START.equals(reason)) { startCheckRan = true; } for (VersionCheckClientListener l : listeners) { l.versionCheckStarted(reason); } } } catch (Throwable t) { Debug.out(t); } if (v6) { if (enable_v6) { try { check_mon.enter(); long time_diff = SystemTime.getCurrentTime() - last_check_time_v6; force = force || time_diff > CACHE_PERIOD || time_diff < 0; if (last_check_data_v6 == null || last_check_data_v6.size() == 0 || force) { // if we've never checked before then we go ahead even if the "only_if_cached" // flag is set as its had not chance of being cached yet! if (only_if_cached && last_check_data_v6 != null) { return (new HashMap()); } try { last_check_data_v6 = performVersionCheck(constructVersionCheckMessage(reason), true, true, true); if (last_check_data_v6 != null && last_check_data_v6.size() > 0) { COConfigurationManager.setParameter("versioncheck.cache.v6", last_check_data_v6); } } catch (SocketException t) { // internet is broken // Debug.out(t.getClass().getName() + ": " + t.getMessage()); } catch (UnknownHostException t) { // dns is broken // Debug.out(t.getClass().getName() + ": " + t.getMessage()); } catch (Throwable t) { Debug.out(t); last_check_data_v6 = new HashMap(); } } else { Logger.log( new LogEvent( LOGID, "VersionCheckClient is using " + "cached version check info. Using " + last_check_data_v6.size() + " reply keys.")); } } finally { check_mon.exit(); } } if (last_check_data_v6 == null) last_check_data_v6 = new HashMap(); return last_check_data_v6; } else { try { check_mon.enter(); long time_diff = SystemTime.getCurrentTime() - last_check_time_v4; force = force || time_diff > CACHE_PERIOD || time_diff < 0; if (last_check_data_v4 == null || last_check_data_v4.size() == 0 || force) { // if we've never checked before then we go ahead even if the "only_if_cached" // flag is set as its had not chance of being cached yet! if (only_if_cached && last_check_data_v4 != null) { return (new HashMap()); } try { last_check_data_v4 = performVersionCheck(constructVersionCheckMessage(reason), true, true, false); if (last_check_data_v4 != null && last_check_data_v4.size() > 0) { COConfigurationManager.setParameter("versioncheck.cache.v4", last_check_data_v4); } // clear down any plugin-specific data that has successfully been sent to the version // server try { if (AzureusCoreFactory.isCoreAvailable()) { // installed plugin IDs PluginInterface[] plugins = AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaces(); for (int i = 0; i < plugins.length; i++) { PluginInterface plugin = plugins[i]; Map data = plugin .getPluginconfig() .getPluginMapParameter("plugin.versionserver.data", null); if (data != null) { plugin .getPluginconfig() .setPluginMapParameter("plugin.versionserver.data", new HashMap()); } } } } catch (Throwable e) { } } catch (UnknownHostException t) { // no internet Debug.outNoStack( "VersionCheckClient - " + t.getClass().getName() + ": " + t.getMessage()); } catch (IOException t) { // General connection problem. Debug.outNoStack( "VersionCheckClient - " + t.getClass().getName() + ": " + t.getMessage()); } catch (Throwable t) { Debug.out(t); last_check_data_v4 = new HashMap(); } } else { if (Logger.isEnabled()) Logger.log( new LogEvent( LOGID, "VersionCheckClient is using " + "cached version check info. Using " + last_check_data_v4.size() + " reply keys.")); } } finally { check_mon.exit(); } if (last_check_data_v4 == null) last_check_data_v4 = new HashMap(); last_feature_flag_cache_time = 0; return last_check_data_v4; } }