Java Code Examples for java.net.InetAddress

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/gameserver/.

Source file: SocketConnector.java

  35 
vote

SocketConnector(GameServer s){
  server=s;
  try {
    InetAddress address=InetAddress.getByName(GameOptions.host);
    InetSocketAddress bindAddr=new InetSocketAddress(address,GameOptions.port);
    socket=new ServerSocket();
    socket.bind(bindAddr);
    socket.setSoTimeout(1000);
  }
 catch (  IOException e) {
    System.err.println("Cannot resolve/bind to " + GameOptions.host + ":"+ GameOptions.port);
    e.printStackTrace();
  }
}
 

Example 2

From project AdminCmd, under directory /src/main/java/be/Balor/Listeners/Features/.

Source file: ACIpCheckListener.java

  32 
vote

@EventHandler public void onJoin(final PlayerJoinEvent event){
  final Player p=event.getPlayer();
  final InetAddress address=p.getAddress().getAddress();
  final HashMap<String,String> replace=new HashMap<String,String>();
  final Player sameIP=addIP(p,address);
  if (sameIP != null) {
    replace.put("player",Utils.getPlayerName(p));
    replace.put("player2",Utils.getPlayerName(sameIP));
    replace.put("ip",address.toString().substring(1));
    broadcastIP(replace);
  }
}
 

Example 3

From project airlift, under directory /dbpool/src/test/java/io/airlift/dbpool/.

Source file: DatabaseIpAddressUtilTest.java

  32 
vote

private void verifyIpAddressConversion(String ipString,int expectedJavaIpAddress,int expectedDatabaseIpAddress) throws UnknownHostException {
  InetAddress address=InetAddress.getByName(ipString);
  int javaIpAddress=address.hashCode();
  assertEquals(javaIpAddress,expectedJavaIpAddress);
  int databaseIpAddress=toDatabaseIpAddress(javaIpAddress);
  assertEquals(databaseIpAddress,expectedDatabaseIpAddress);
  assertEquals(fromDatabaseIpAddress(databaseIpAddress),javaIpAddress);
}
 

Example 4

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/conn/params/.

Source file: ConnRouteParams.java

  32 
vote

/** 
 * Obtains the  {@link ConnRoutePNames#LOCAL_ADDRESS LOCAL_ADDRESS}parameter value. There is no special value that would automatically be mapped to <code>null</code>. You can use the wildcard address (0.0.0.0 for IPv4, :: for IPv6) to override a specific local address in a hierarchy.
 * @param params    the parameters in which to look up
 * @return  the local address set in the argument parameters, or<code>null</code> if not set
 */
public static InetAddress getLocalAddress(HttpParams params){
  if (params == null) {
    throw new IllegalArgumentException("Parameters must not be null.");
  }
  InetAddress local=(InetAddress)params.getParameter(LOCAL_ADDRESS);
  return local;
}
 

Example 5

From project android-xbmcremote, under directory /src/org/xbmc/eventclient/.

Source file: EventClient.java

  32 
vote

/** 
 * Stops the XBMC EventClient (especially the Ping-Thread)
 * @throws IOException
 */
public void stopClient() throws IOException {
  final InetAddress addr=mHostAddress;
  if (addr != null) {
    mPingThread.giveup();
    mPingThread.interrupt();
    PacketBYE p=new PacketBYE();
    p.send(mHostAddress,mHostPort);
  }
}
 

Example 6

From project BeeQueue, under directory /src/org/beequeue/host/.

Source file: Host.java

  32 
vote

public static Host localHost(){
  InetAddress inetAddress;
  try {
    inetAddress=InetAddress.getLocalHost();
    Host host=new Host();
    host.ip=inetAddress.getHostAddress();
    host.fqdn=inetAddress.getCanonicalHostName();
    host.hostName=inetAddress.getHostName();
    return host;
  }
 catch (  UnknownHostException e) {
    throw new RuntimeException(e);
  }
}
 

Example 7

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.

Source file: Utils.java

  32 
vote

/** 
 * Check if phone can connect to a specific host. Does not work.... ENHANCE: Find a way to make network host checks possible
 * @return
 */
public static int lookupHost(String hostname){
  InetAddress inetAddress;
  try {
    inetAddress=InetAddress.getByName(hostname);
  }
 catch (  UnknownHostException e) {
    return -1;
  }
  byte[] addrBytes;
  int addr;
  addrBytes=inetAddress.getAddress();
  addr=((addrBytes[3] & 0xff) << 24) | ((addrBytes[2] & 0xff) << 16) | ((addrBytes[1] & 0xff) << 8)| (addrBytes[0] & 0xff);
  return addr;
}
 

Example 8

From project cas, under directory /cas-server-support-ldap/src/main/java/org/jasig/cas/adaptors/ldap/remote/.

Source file: RemoteAddressAuthenticationHandler.java

  32 
vote

public boolean authenticate(final Credentials credentials) throws AuthenticationException {
  final RemoteAddressCredentials c=(RemoteAddressCredentials)credentials;
  try {
    final InetAddress inetAddress=InetAddress.getByName(c.getRemoteAddress().trim());
    return containsAddress(this.inetNetwork,this.inetNetmask,inetAddress);
  }
 catch (  final UnknownHostException e) {
    return false;
  }
}
 

Example 9

From project ChessCraft, under directory /src/main/java/fr/free/jchecs/core/.

Source file: PGNUtilsTest.java

  32 
vote

/** 
 * Pour que JUnit puisse instancier les tests.
 */
public PGNUtilsTest(){
  String site="?";
  try {
    final InetAddress lh=InetAddress.getLocalHost();
    site=lh.getHostName();
  }
 catch (  final UnknownHostException e) {
  }
  _site=site;
}
 

Example 10

From project chililog-server, under directory /src/test/java/org/chililog/server/engine/.

Source file: InternalLog4JAppenderTest.java

  32 
vote

@Before public void testSetup() throws Exception {
  _db=MongoConnection.getInstance().getConnection();
  assertNotNull(_db);
  DBCollection coll=_db.getCollection(InternalLog4JAppender.MONGODB_COLLECTION_NAME);
  if (coll != null) {
    DBObject query=new BasicDBObject();
    coll.remove(query);
  }
  InetAddress addr=InetAddress.getLocalHost();
  _machineName=addr.getHostName();
}
 

Example 11

From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/.

Source file: EnvironmentUtil.java

  32 
vote

public static String getHostFQDN() throws EnvironmentException {
  try {
    InetAddress addr=InetAddress.getLocalHost();
    byte[] ipAddr=addr.getAddress();
    return addr.getHostName();
  }
 catch (  UnknownHostException e) {
    throw new EnvironmentException("Unable to determine hostname",e);
  }
}
 

Example 12

From project codjo-data-process, under directory /codjo-data-process-gui/src/main/java/net/codjo/dataprocess/gui/plugin/.

Source file: DataProcessGuiPlugin.java

  32 
vote

private UserLoginTracker buildUserLoginTracker() throws UnknownHostException {
  InetAddress localhostAddress=Inet4Address.getLocalHost();
  String ip=localhostAddress.getHostAddress();
  String hostname=localhostAddress.getHostName();
  User user=configuration.getUser();
  return new UserLoginTracker(user.getUserName(),user.getCurrentRepository(),ip,hostname,null);
}
 

Example 13

From project commons-j, under directory /src/test/java/nerds/antelax/commons/net/pubsub/.

Source file: PubSubTest.java

  32 
vote

/** 
 * Creates some interesting server configurations to test: <ul> <li>single port</li> <li>two ports</li> <li>three ports</li> <li>random between 5 and 10 ports</li> </ul>
 * @throws UnknownHostException
 */
@DataProvider(name="server-addresses") public Object[][] serverAddresses() throws UnknownHostException {
  final InetAddress loopback=InetAddress.getByName("127.0.0.1");
  final InetAddress local=InetAddress.getLocalHost();
  final Function<Integer,InetSocketAddress> serverAddressBuilder=new Function<Integer,InetSocketAddress>(){
    @Override public InetSocketAddress apply(    final Integer input){
      return new InetSocketAddress(input % 2 == 0 ? loopback : local,PubSubServer.DEFAULT_ADDRESS.getPort() + input);
    }
  }
;
  final int random=new SecureRandom().nextInt(5) + 5;
  final Collection<Integer> randomCount=new ArrayList<Integer>(random);
  for (int pos=0; pos < random; ++pos)   randomCount.add(6 + pos);
  return new Object[][]{new Object[]{Collections2.transform(Arrays.asList(0),serverAddressBuilder)},new Object[]{Collections2.transform(Arrays.asList(1,2),serverAddressBuilder)},new Object[]{Collections2.transform(Arrays.asList(3,4,5),serverAddressBuilder)},new Object[]{Collections2.transform(randomCount,serverAddressBuilder)}};
}
 

Example 14

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/server/.

Source file: RequestProcessorBase.java

  31 
vote

public void run(){
  try {
    InetAddress addr=socket.getInetAddress();
    logger.debug("Processing request from " + addr);
    BufferedWriter w=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    if (!trustedAddresses.contains(addr)) {
      FacilityConfig f=facilityMapper.lookup(null,null,addr);
      if (f == null) {
        logger.debug("Unknown facility: IP is " + addr);
        if (!allowUnknownClients) {
          w.append("Proxy has no facility details for " + addr + "\r\n").flush();
          return;
        }
      }
    }
    w.append(AbstractMessage.ACCEPTED_IP_TAG + "\r\n").flush();
    InputStream is=socket.getInputStream();
    RequestReader reader=new RequestReaderImpl(facilityMapper,socket.getInetAddress());
    Request m=reader.read(is);
    doProcess(m,w);
  }
 catch (  IOException ex) {
    logger.error("IO error",ex);
  }
catch (  AclsException ex) {
    logger.error("ACLS error",ex);
  }
catch (  Throwable ex) {
    logger.error("Unexpected error",ex);
  }
 finally {
    try {
      socket.close();
    }
 catch (    IOException ex) {
    }
  }
}
 

Example 15

From project android-share-menu, under directory /src/com/eggie5/.

Source file: post_to_eggie5.java

  31 
vote

private void SendRequest(String data_string){
  try {
    String xmldata="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<photo><photo>" + data_string + "</photo><caption>via android - "+ new Date().toString()+ "</caption></photo>";
    String hostname="eggie5.com";
    String path="/photos";
    int port=80;
    InetAddress addr=InetAddress.getByName(hostname);
    Socket sock=new Socket(addr,port);
    BufferedWriter wr=new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
    wr.write("POST " + path + " HTTP/1.1\r\n");
    wr.write("Host: eggie5.com\r\n");
    wr.write("Content-Length: " + xmldata.length() + "\r\n");
    wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");
    wr.write("Accept: text/xml\r\n");
    wr.write("\r\n");
    wr.write(xmldata);
    wr.flush();
    BufferedReader rd=new BufferedReader(new InputStreamReader(sock.getInputStream()));
    String line;
    while ((line=rd.readLine()) != null) {
      Log.v(this.getClass().getName(),line);
    }
  }
 catch (  Exception e) {
    Log.e(this.getClass().getName(),"Upload failed",e);
  }
}
 

Example 16

From project android-vpn-server, under directory /src/com/android/server/vpn/.

Source file: VpnService.java

  31 
vote

private void saveLocalIpAndInterface(String serverIp) throws IOException {
  DatagramSocket s=new DatagramSocket();
  int port=80;
  s.connect(InetAddress.getByName(serverIp),port);
  InetAddress localIp=s.getLocalAddress();
  mLocalIp=localIp.getHostAddress();
  NetworkInterface localIf=NetworkInterface.getByInetAddress(localIp);
  mLocalIf=(localIf == null) ? null : localIf.getName();
  if (TextUtils.isEmpty(mLocalIf)) {
    throw new IOException("Local interface is empty!");
  }
  if (DBG) {
    Log.d(TAG,"  Local IP: " + mLocalIp + ", if: "+ mLocalIf);
  }
}
 

Example 17

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: Connector.java

  31 
vote

public Connector(String protocol,String host,int port,int timeout,boolean discovery){
  if (protocol != null && !protocol.equals(""))   this.protocol=protocol;
  if (host != null && !host.equals(""))   this.hostname=host;
 else {
    try {
      InetAddress addr=InetAddress.getLocalHost();
      this.hostname=getHostNameForAddressWithoutLookup(addr);
    }
 catch (    Exception e) {
      this.hostname="localhost";
    }
  }
  this.port=port;
  this.timeout=timeout;
  this.discovery=discovery;
}
 

Example 18

From project apg, under directory /src/org/thialfihar/android/apg/.

Source file: HkpKeyServer.java

  31 
vote

private String query(String request) throws QueryException, HttpError {
  InetAddress ips[];
  try {
    ips=InetAddress.getAllByName(mHost);
  }
 catch (  UnknownHostException e) {
    throw new QueryException(e.toString());
  }
  for (int i=0; i < ips.length; ++i) {
    try {
      String url="http://" + ips[i].getHostAddress() + ":"+ mPort+ request;
      URL realUrl=new URL(url);
      HttpURLConnection conn=(HttpURLConnection)realUrl.openConnection();
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(25000);
      conn.connect();
      int response=conn.getResponseCode();
      if (response >= 200 && response < 300) {
        return readAll(conn.getInputStream(),conn.getContentEncoding());
      }
 else {
        String data=readAll(conn.getErrorStream(),conn.getContentEncoding());
        throw new HttpError(response,data);
      }
    }
 catch (    MalformedURLException e) {
    }
catch (    IOException e) {
    }
  }
  throw new QueryException("querying server(s) for '" + mHost + "' failed");
}
 

Example 19

From project Arecibo, under directory /alert/src/main/java/com/ning/arecibo/alert/email/.

Source file: EmailManager.java

  31 
vote

@Inject public EmailManager(final AlertServiceConfig alertServiceConfig){
  this.alertServiceConfig=alertServiceConfig;
  String hostName;
  String hostIp;
  try {
    final InetAddress localHost=InetAddress.getLocalHost();
    hostName=localHost.getHostName();
    hostIp=localHost.getHostAddress();
  }
 catch (  UnknownHostException uhEx) {
    log.warn("UnknownHostException: won't be able to append sending host info to outgoing email");
    log.info(uhEx);
    hostName="";
    hostIp="";
  }
  sendingHostSignature=String.format("\n\nSent by Arecibo Alert Service: %s (%s)",hostName,hostIp);
}
 

Example 20

From project astyanax, under directory /src/main/java/com/netflix/astyanax/connectionpool/.

Source file: Host.java

  31 
vote

/** 
 * Construct a Host from a host:port combination.  The defaultPort is provided in case the hostAndPort2 value does not have a port specified.
 * @param hostAndPort
 * @param defaultPort
 */
public Host(String hostAndPort,int defaultPort){
  String tempHost=parseHostFromHostAndPort(hostAndPort);
  this.port=parsePortFromHostAndPort(hostAndPort,defaultPort);
  Matcher match=ipPattern.matcher(tempHost);
  String workHost;
  String workIpAddress;
  if (match.matches()) {
    workHost=tempHost;
    workIpAddress=tempHost;
  }
 else {
    try {
      InetAddress address=InetAddress.getByName(tempHost);
      workHost=address.getHostName();
      workIpAddress=address.getHostAddress();
    }
 catch (    UnknownHostException e) {
      workHost=tempHost;
      workIpAddress=tempHost;
    }
  }
  this.host=workHost;
  this.ipAddress=workIpAddress;
  this.name=String.format("%s(%s):%d",tempHost,this.ipAddress,this.port);
  this.url=String.format("%s:%d",this.host,this.port);
}
 

Example 21

From project aws-tasks, under directory /src/main/java/datameer/awstasks/aws/ec2/support/.

Source file: Ec2SocketFactory.java

  31 
vote

private SocketAddress translateSocketAddress(InetSocketAddress endpoint){
  InetAddress address=endpoint.getAddress();
  String hostName;
  if (address != null) {
    hostName=address.getHostName();
  }
 else {
    hostName=endpoint.getHostName();
  }
  String publicHostname=_publicAddressesByPrivateAddresses.get(hostName);
  if (publicHostname != null) {
    if (LOG.isTraceEnabled()) {
      LOG.trace("translate private address '" + hostName + "' into public address '"+ publicHostname+ "'");
    }
    endpoint=new InetSocketAddress(publicHostname,endpoint.getPort());
  }
  return endpoint;
}
 

Example 22

From project bagheera, under directory /src/main/java/com/mozilla/bagheera/util/.

Source file: HttpUtil.java

  31 
vote

public static byte[] getRemoteAddr(HttpRequest request,InetAddress channelRemoteAddr){
  String forwardedAddr=request.getHeader(X_FORWARDED_FOR);
  byte[] addrBytes=null;
  if (forwardedAddr != null) {
    InetAddress addr;
    try {
      addr=InetAddress.getByName(forwardedAddr);
      addrBytes=addr.getAddress();
    }
 catch (    UnknownHostException e) {
    }
  }
  if (addrBytes == null) {
    addrBytes=channelRemoteAddr.getAddress();
  }
  return addrBytes;
}
 

Example 23

From project BetterShop_1, under directory /src/me/jascotty2/lib/bukkit/.

Source file: ServerInfo.java

  31 
vote

public static String serverIPs(boolean mask){
  if (sip == null) {
    sip="";
    try {
      InetAddress localaddr=InetAddress.getLocalHost();
      sip=localaddr.getHostName();
      try {
        URL autoIP=new URL("http://automation.whatismyip.com/n09230945.asp");
        BufferedReader in=new BufferedReader(new InputStreamReader(autoIP.openStream()));
        sip+=":" + (in.readLine()).trim();
      }
 catch (      Exception e) {
        sip+=":ukpip";
      }
      for (      InetAddress i : InetAddress.getAllByName(localaddr.getHostName())) {
        if (!i.isLoopbackAddress()) {
          sip+=":" + i.getHostAddress();
        }
      }
    }
 catch (    Exception ex) {
      sip+=":ukh";
    }
  }
  if (mask && sipM == null) {
    try {
      sipM=SUIDmd5Str(sip);
    }
 catch (    Exception ex) {
      sipM=shorten(sip.replace(":","").replace(".",""),16);
    }
  }
  return mask ? sipM : sip;
}
 

Example 24

From project BioMAV, under directory /ParrotControl/JavaDroneControl/src/nl/ru/ai/projects/parrot/dronecontrol/javadronecontrol/.

Source file: DroneGroundStation.java

  31 
vote

public void connect(String remoteAddress){
  disconnect();
  try {
    InetAddress remoteInetAddress=InetAddress.getByName(remoteAddress);
    controlCommandInterface.connect(remoteInetAddress);
    try {
      navdataChannel.connect(remoteInetAddress);
      try {
        vision.connect(remoteInetAddress,this);
      }
 catch (      IOException e) {
        navdataChannel.disconnect();
        throw e;
      }
      controlAbstractionThread=new Thread(this);
      controlAbstractionThread.start();
    }
 catch (    IOException e) {
      controlCommandInterface.disconnect();
      throw e;
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 25

From project blacktie, under directory /stompconnect-1.0/src/main/java/org/codehaus/stomp/tcp/.

Source file: TcpTransportServer.java

  31 
vote

public void start() throws IOException {
  URI bind=bindLocation;
  String host=bind.getHost();
  host=(host == null || host.length() == 0) ? "localhost" : host;
  InetAddress addr=InetAddress.getByName(host);
  try {
    this.serverSocket=serverSocketFactory.createServerSocket(bind.getPort(),backlog,addr);
    this.serverSocket.setSoTimeout(2000);
  }
 catch (  IOException e) {
    throw IOExceptionSupport.create("Failed to bind to server socket: " + bind + " due to: "+ e,e);
  }
  try {
    connectURI=new URI(bind.getScheme(),bind.getUserInfo(),bind.getHost(),serverSocket.getLocalPort(),bind.getPath(),bind.getQuery(),bind.getFragment());
  }
 catch (  URISyntaxException e) {
    throw IOExceptionSupport.create(e);
  }
  log.info("Listening for connections at: " + connectURI);
  runner=new Thread(this,"StompConnect Server Thread: " + toString());
  runner.setDaemon(daemon);
  runner.start();
}
 

Example 26

From project cloudify, under directory /CLI/Archive/.

Source file: AddBareMetalInstance.java

  31 
vote

private boolean isMachineAvailable(final String node,final Set<String> activeNodes) throws UnknownHostException, ErrorStatusException {
  final Set<String> nodeNames=new HashSet<String>();
  nodeNames.add(node);
  final InetAddress address=InetAddress.getByName(node);
  nodeNames.add(address.getHostAddress());
  nodeNames.add(address.getHostName());
  final int sizeBefore=nodeNames.size();
  nodeNames.removeAll(activeNodes);
  final int sizeAfter=nodeNames.size();
  if (sizeAfter != sizeBefore) {
    return false;
  }
  try {
    AgentlessInstaller.checkConnection(node,22,10,TimeUnit.SECONDS);
  }
 catch (  final Exception e) {
    logger.info("Failed connection test on port 22 for machine: " + node);
    return false;
  }
  return true;
}
 

Example 27

From project CMM-data-grabber, under directory /paul/src/main/java/au/edu/uq/cmm/paul/servlet/.

Source file: ConfigurationManager.java

  31 
vote

private void checkAddressability(String address,String localHostId,Long id,Map<String,String> diags,EntityManager em){
  InetAddress inetAddr;
  try {
    inetAddr=InetAddress.getByName(address);
  }
 catch (  UnknownHostException ex) {
    addDiag(diags,"address",ex.getMessage());
    return;
  }
  if (localHostId != null) {
    return;
  }
  TypedQuery<Object[]> query;
  if (id == null) {
    query=em.createQuery("select f.facilityName, f.address from Facility f " + "where f.localHostId = NULL",Object[].class);
  }
 else {
    query=em.createQuery("select f.facilityName, f.address from Facility f " + "where f.localHostId = NULL and f.id != :id",Object[].class);
    query.setParameter("id",id.longValue());
  }
  List<Object[]> others=query.getResultList();
  for (  Object[] other : others) {
    try {
      InetAddress otherAddr=InetAddress.getByName((String)other[1]);
      if (otherAddr.equals(inetAddr)) {
        addDiag(diags,"address","address resolves to an IP address used by " + "another facility ('" + other[0] + "').  "+ "Resolve the address conflict or use a local host id");
      }
    }
 catch (    UnknownHostException ex) {
      LOG.warn("Cannot resolve hostname / address " + other[1] + " for facility "+ other[0]);
    }
  }
}
 

Example 28

From project cometd, under directory /cometd-java/cometd-java-oort/src/test/java/org/cometd/oort/.

Source file: OortMulticastConfigurerTest.java

  31 
vote

@Before public void assumeMulticast() throws Exception {
  InetAddress multicastAddress=InetAddress.getByName("239.255.0.1");
  MulticastSocket receiver=new MulticastSocket(0);
  receiver.joinGroup(multicastAddress);
  MulticastSocket sender=new MulticastSocket();
  sender.setTimeToLive(1);
  sender.send(new DatagramPacket(new byte[]{1},0,1,multicastAddress,receiver.getLocalPort()));
  sender.close();
  byte[] buffer=new byte[1];
  receiver.setSoTimeout(1000);
  try {
    receiver.receive(new DatagramPacket(buffer,0,buffer.length));
  }
 catch (  SocketTimeoutException x) {
    Assume.assumeNoException(x);
  }
 finally {
    receiver.close();
  }
}
 

Example 29

From project comm, under directory /src/main/java/io/s4/comm/core/.

Source file: GenericListener.java

  31 
vote

public GenericListener(String zkaddress,String appName,Object listenerConfig,Deserializer deserializer){
  this.zkAddress=zkAddress;
  this.deserializer=deserializer;
  try {
    Map<String,String> map=(Map<String,String>)listenerConfig;
    String mode=map.get("mode");
    int port=Integer.parseInt(map.get("port"));
    if (mode.equals("multicast")) {
      InetAddress inetAddress=InetAddress.getByName(map.get("channel"));
      socket=new MulticastSocket(port);
      ((MulticastSocket)socket).joinGroup(inetAddress);
    }
    if (mode.equals("unicast")) {
      socket=new DatagramSocket(port);
    }
    String udpBufferSize=System.getProperty("udp.buffer.size");
    if (udpBufferSize == null) {
      udpBufferSize="4194302";
    }
    socket.setReceiveBufferSize(Integer.parseInt(udpBufferSize));
    bs=new byte[BUFFER_LENGTH];
    dgram=new DatagramPacket(bs,bs.length);
  }
 catch (  IOException e) {
    logger.error("error creating listener",e);
    throw new RuntimeException(e);
  }
}
 

Example 30

From project CommitCoin, under directory /src/com/google/bitcoin/discovery/.

Source file: IrcDiscovery.java

  31 
vote

static ArrayList<InetSocketAddress> parseUserList(String[] userNames) throws UnknownHostException {
  ArrayList<InetSocketAddress> addresses=new ArrayList<InetSocketAddress>();
  for (  String user : userNames) {
    if (!user.startsWith("u")) {
      continue;
    }
    byte[] addressBytes;
    try {
      addressBytes=Base58.decodeChecked(user.substring(1));
    }
 catch (    AddressFormatException e) {
      log.warn("IRC nick does not parse as base58: " + user);
      continue;
    }
    if (addressBytes.length != 6) {
      continue;
    }
    byte[] ipBytes=new byte[]{addressBytes[0],addressBytes[1],addressBytes[2],addressBytes[3]};
    int port=Utils.readUint16BE(addressBytes,4);
    InetAddress ip;
    try {
      ip=InetAddress.getByAddress(ipBytes);
    }
 catch (    UnknownHostException e) {
      continue;
    }
    InetSocketAddress address=new InetSocketAddress(ip,port);
    addresses.add(address);
  }
  return addresses;
}
 

Example 31

From project advanced, under directory /management/src/main/java/org/neo4j/management/impl/.

Source file: HotspotManagementSupport.java

  29 
vote

private JMXServiceURL getUrlFrom(String url){
  if (url == null)   return null;
  JMXServiceURL jmxUrl;
  try {
    jmxUrl=new JMXServiceURL(url);
  }
 catch (  MalformedURLException e1) {
    return null;
  }
  String host=null;
  try {
    host=InetAddress.getLocalHost().getHostAddress();
  }
 catch (  UnknownHostException ok) {
  }
  if (host == null) {
    host=jmxUrl.getHost();
  }
  try {
    return new JMXServiceURL(jmxUrl.getProtocol(),host,jmxUrl.getPort(),jmxUrl.getURLPath());
  }
 catch (  MalformedURLException e) {
    return null;
  }
}
 

Example 32

From project agit, under directory /agit-test-utils/src/main/java/com/madgag/agit/.

Source file: GitTestUtils.java

  29 
vote

public static String gitServerHostAddress() throws IOException, UnknownHostException {
  File hostAddressFile=new File(Environment.getExternalStorageDirectory(),"agit-integration-test.properties");
  Properties properties=new Properties();
  if (hostAddressFile.exists()) {
    properties.load(new FileInputStream(hostAddressFile));
  }
  String[] hostAddresses=properties.getProperty("gitserver.host.address","10.0.2.2").split(",");
  for (  String hostAddress : hostAddresses) {
    if (InetAddress.getByName(hostAddress).isReachable(1000)) {
      Log.d(TAG,"Using git server host : " + hostAddress);
      return hostAddress;
    }
  }
  throw new RuntimeException("No reachable addresses in " + asList(hostAddresses));
}
 

Example 33

From project android-bankdroid, under directory /src/eu/nullbyte/android/urllib/.

Source file: EasySSLSocketFactory.java

  29 
vote

/** 
 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,java.lang.String,int,java.net.InetAddress,int,org.apache.http.params.HttpParams)
 */
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 sslsock=(SSLSocket)((sock != null) ? sock : createSocket());
  if ((localAddress != null) || (localPort > 0)) {
    if (localPort < 0) {
      localPort=0;
    }
    InetSocketAddress isa=new InetSocketAddress(localAddress,localPort);
    sslsock.bind(isa);
  }
  sslsock.connect(remoteAddress,connTimeout);
  sslsock.setSoTimeout(soTimeout);
  return sslsock;
}
 

Example 34

From project android-client_1, under directory /src/com/googlecode/asmack/connection/impl/.

Source file: TcpConnection.java

  29 
vote

/** 
 * Start the tcp connection to a given ip/port pair.
 * @param addresse InetAddress The target internet address.
 * @param port int The target port.
 * @throws XmppException In case of a lower level exception.
 */
protected void connect(InetAddress addresse,int port) throws XmppException {
  SocketFactory socketFactory=SocketFactory.getDefault();
  try {
    socket=socketFactory.createSocket(addresse,port);
    socket.setKeepAlive(false);
    socket.setSoTimeout(3 * 60 * 1000);
    socket.setTcpNoDelay(true);
  }
 catch (  IOException e) {
    close();
    throw new XmppTransportException("Can't connect",e);
  }
  FeatureNegotiationEngine engine;
  try {
    engine=new FeatureNegotiationEngine(socket);
  }
 catch (  XmlPullParserException e) {
    Log.e(TAG,"can't negotiate",e);
    close();
    throw new XmppMalformedException("Can't connect",e);
  }
catch (  IOException e) {
    Log.e(TAG,"can't negotiate",e);
    close();
    throw new XmppTransportException("Can't connect",e);
  }
  engine.open(account);
  resourceJid=engine.bind(account.getResource());
  if (resourceJid == null) {
    close();
    throw new XmppTransportException("Can't bind");
  }
  Log.d(TAG,"Bound as " + resourceJid);
  xmppInput=engine.getXmppInputStream();
  xmppOutput=engine.getXmppOutputStream();
}
 

Example 35

From project android-rackspacecloud, under directory /main/java/net/elasticgrid/rackspace/cloudservers/.

Source file: Addresses.java

  29 
vote

public Addresses(net.elasticgrid.rackspace.cloudservers.internal.Addresses addresses) throws UnknownHostException {
  Public publicAddresses=addresses.getPublic();
  this.publicAddresses=new ArrayList<InetAddress>(publicAddresses.getAddressLists().size());
  for (  net.elasticgrid.rackspace.cloudservers.internal.Address address : publicAddresses.getAddressLists()) {
    this.publicAddresses.add(InetAddress.getByName(address.getAddr()));
  }
  Private privateAddresses=addresses.getPrivate();
  this.privateAddresses=new ArrayList<InetAddress>(privateAddresses.getAddressLists().size());
  for (  net.elasticgrid.rackspace.cloudservers.internal.Address address : privateAddresses.getAddressLists()) {
    this.privateAddresses.add(InetAddress.getByName(address.getAddr()));
  }
}
 

Example 36

From project android-xbmcremote-sandbox, under directory /src/org/xbmc/android/zeroconf/.

Source file: DiscoveryService.java

  29 
vote

@Override protected void onHandleIntent(Intent intent){
  try {
    final int ipAddress=mWifiManager.getConnectionInfo().getIpAddress();
    if (ipAddress != 0) {
      mWifiAddress=InetAddress.getByName(android.text.format.Formatter.formatIpAddress(ipAddress));
      Log.i(TAG,"Discovering XBMC hosts through " + mWifiAddress.getHostAddress() + "...");
    }
 else {
      Log.i(TAG,"Discovering XBMC hosts on all interfaces...");
    }
  }
 catch (  UnknownHostException e) {
    Log.e(TAG,"Cannot parse Wifi IP address.",e);
  }
  final ResultReceiver receiver=intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
  acquireMulticastLock();
  new Thread(){
    @Override public void run(){
      listen(receiver);
    }
  }
.start();
  try {
    Thread.sleep(TIMEOUT);
  }
 catch (  InterruptedException e) {
    Log.e(TAG,"Error sleeping " + TIMEOUT + "ms.",e);
  }
  receiver.send(STATUS_FINISHED,Bundle.EMPTY);
  releaseMulticastLock();
}
 

Example 37

From project android_8, under directory /src/com/defuzeme/network/.

Source file: Broadcaster.java

  29 
vote

@Override protected void onPreExecute(){
  DefuzeMe.Gui.showProgress(string.SearchingForClients);
  try {
    this._address=InetAddress.getByName(Settings._BCastSendAddress);
    this._rSocket=new MulticastSocket(Settings._BCastRecvPort);
    this._sSocket=new DatagramSocket();
    this._rSocket.joinGroup(InetAddress.getByName(Settings._BCastRecvAddress));
    this._rSocket.setSoTimeout(Settings._TimeOut);
  }
 catch (  UnknownHostException exception) {
    Log.w(this.getClass().getName(),"Unknown host : " + exception.toString());
  }
catch (  SocketException exception) {
    Log.e(this.getClass().getName(),"Socket exception : " + exception.toString());
  }
catch (  IOException exception) {
    Log.w(this.getClass().getName(),"IO Exception : " + exception.toString());
  }
}
 

Example 38

From project apb, under directory /modules/apb-base/src/apb/testrunner/output/.

Source file: XmlTestReport.java

  29 
vote

private static String getHostname(){
  try {
    return InetAddress.getLocalHost().getHostName();
  }
 catch (  UnknownHostException e) {
    return "localhost";
  }
}
 

Example 39

From project ardverk-commons, under directory /src/main/java/org/ardverk/net/.

Source file: AddressTracker.java

  29 
vote

/** 
 * Creates an  {@link AddressTracker}
 */
public AddressTracker(InetAddress address,NetworkMask mask,int count){
  if (mask == null) {
    throw new NullPointerException("mask");
  }
  if (count < 0) {
    throw new IllegalArgumentException("count=" + count);
  }
  this.current=address;
  this.mask=mask;
  this.history=new FixedSizeHashSet<ByteBuffer>(count);
}
 

Example 40

From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/codec/bencode/.

Source file: MessageOutputStream.java

  29 
vote

@Override protected void writeCustom(Object obj) throws IOException {
  if (obj instanceof InetAddress) {
    writeInetAddress((InetAddress)obj);
  }
 else   if (obj instanceof SocketAddress) {
    writeSocketAddress((SocketAddress)obj);
  }
 else   if (obj instanceof KUID) {
    writeKUID((KUID)obj);
  }
 else   if (obj instanceof MessageId) {
    writeMessageId((MessageId)obj);
  }
 else   if (obj instanceof Contact) {
    writeContact((Contact)obj);
  }
 else   if (obj instanceof Message) {
    writeMessage((Message)obj);
  }
 else   if (obj instanceof Key) {
    writeKey((Key)obj);
  }
 else {
    super.writeCustom(obj);
  }
}
 

Example 41

From project arquillian-container-jbossas, under directory /jbossas-managed-4.2/src/main/java/org/jboss/arquillian/container/jbossas/managed_4_2/.

Source file: ManagementViewParser.java

  29 
vote

private static HTTPContext extractHTTPContext(MBeanServerConnection connection) throws Exception {
  Set<ObjectName> connectors=connection.queryNames(new ObjectName("jboss.web:*,type=Connector"),null);
  for (  ObjectName connector : connectors) {
    String protocol=(String)connection.getAttribute(connector,"protocol");
    if (protocol.contains("HTTP")) {
      String address=((InetAddress)connection.getAttribute(connector,"address")).getHostAddress();
      Integer port=Integer.parseInt(connector.getKeyProperty("port"));
      return new HTTPContext(address,port);
    }
  }
  return null;
}
 

Example 42

From project arquillian_deprecated, under directory /containers/jbossas-remote-5/src/main/java/org/jboss/arquillian/container/jbossas/remote_5_0/.

Source file: ManagementViewParser.java

  29 
vote

/** 
 * @param management
 * @return
 */
private static HTTPContext extractHTTPContext(MBeanServerConnection connection) throws Exception {
  Set<ObjectName> connectors=connection.queryNames(new ObjectName("jboss.web:*,type=Connector"),null);
  for (  ObjectName connector : connectors) {
    String protocol=(String)connection.getAttribute(connector,"protocol");
    if (protocol.contains("HTTP")) {
      String address=((InetAddress)connection.getAttribute(connector,"address")).getHostAddress();
      Integer port=Integer.parseInt(connector.getKeyProperty("port"));
      return new HTTPContext(address,port);
    }
  }
  return null;
}
 

Example 43

From project AsmackService, under directory /src/com/googlecode/asmack/connection/impl/.

Source file: TcpConnection.java

  29 
vote

/** 
 * Start the tcp connection to a given ip/port pair.
 * @param addresse InetAddress The target internet address.
 * @param port int The target port.
 * @throws XmppException In case of a lower level exception.
 */
protected void connect(InetAddress addresse,int port) throws XmppException {
  SocketFactory socketFactory=SocketFactory.getDefault();
  try {
    socket=socketFactory.createSocket(addresse,port);
    socket.setKeepAlive(false);
    socket.setSoTimeout(3 * 60 * 1000);
    socket.setTcpNoDelay(true);
  }
 catch (  IOException e) {
    close();
    throw new XmppTransportException("Can't connect",e);
  }
  FeatureNegotiationEngine engine;
  try {
    engine=new FeatureNegotiationEngine(socket);
  }
 catch (  XmlPullParserException e) {
    close();
    throw new XmppMalformedException("Can't connect",e);
  }
catch (  IOException e) {
    close();
    throw new XmppTransportException("Can't connect",e);
  }
  engine.open(account);
  resourceJid=engine.bind(account.getResource());
  if (resourceJid == null) {
    close();
    throw new XmppTransportException("Can't bind");
  }
  Log.d(TAG,"Bound as " + resourceJid);
  xmppInput=engine.getXmppInputStream();
  xmppOutput=engine.getXmppOutputStream();
}
 

Example 44

From project asterisk-java, under directory /src/integrationtest/org/asteriskjava/fastagi/.

Source file: HangupTest.java

  29 
vote

public static void main(String[] args) throws IOException {
  AgiServerThread agiServerThread=new AgiServerThread();
  agiServerThread.setAgiServer(new DefaultAgiServer());
  agiServerThread.setDaemon(false);
  agiServerThread.startup();
  DefaultAsteriskServer server=new DefaultAsteriskServer("localhost",1234,"manager","obelisk");
  server.initialize();
  server.originateToApplication("SIP/phone-02","AGI","agi://" + InetAddress.getLocalHost().getHostAddress() + "/"+ HangupTest.class.getName()+ ", arg1,,arg3",30000);
}
 

Example 45

From project azkaban, under directory /azkaban/src/java/azkaban/jobs/.

Source file: JobExecutorManager.java

  29 
vote

private void sendSuccessEmail(JobExecution job,Duration duration,String senderAddress,List<String> emailList){
  if ((emailList == null || emailList.isEmpty()) && jobSuccessEmail != null) {
    emailList=Arrays.asList(jobSuccessEmail);
  }
  if (emailList != null && mailman != null) {
    try {
      mailman.sendEmailIfPossible(senderAddress,emailList,"Job '" + job.getId() + "' has completed on "+ InetAddress.getLocalHost().getHostName()+ "!","The job '" + job.getId() + "' completed in "+ PeriodFormat.getDefault().print(duration.toPeriod())+ ".");
    }
 catch (    UnknownHostException uhe) {
      logger.error(uhe);
    }
  }
}
 

Example 46

From project BanHammer, under directory /src/main/java/name/richardson/james/bukkit/banhammer/.

Source file: PlayerListener.java

  29 
vote

/** 
 * Checks if is player banned.
 * @param player the player
 * @return true, if is player banned
 */
private PlayerRecord isPlayerBanned(final String playerName,InetAddress address){
  this.getLogger().debug(this,"checking-for-bans",playerName);
  PlayerRecord record=PlayerRecord.find(database,playerName);
  if (record.isBanned()) {
    return record;
  }
 else   if (this.aliasHandler != null) {
    this.getLogger().debug(this,"checking-for-alias",playerName);
    final Collection<PlayerNameRecord> aliases=this.aliasHandler.getPlayersNames(address);
    for (    final PlayerNameRecord alias : aliases) {
      record=PlayerRecord.find(database,alias.getPlayerName());
      if (record.isBanned()) {
        final String reason=this.localisation.getMessage(this,"alias-ban-reason",record.getName());
        this.handler.banPlayer(playerName,record.getActiveBan(),reason,true);
        return record;
      }
    }
  }
  this.getLogger().debug(this,"player-not-banned",playerName);
  return null;
}
 

Example 47

From project bbb-java, under directory /src/main/java/org/transdroid/util/.

Source file: FakeSocketFactory.java

  29 
vote

@Override 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 sslsock=(SSLSocket)((sock != null) ? sock : createSocket());
  if ((localAddress != null) || (localPort > 0)) {
    if (localPort < 0) {
      localPort=0;
    }
    InetSocketAddress isa=new InetSocketAddress(localAddress,localPort);
    sslsock.bind(isa);
  }
  sslsock.connect(remoteAddress,connTimeout);
  sslsock.setSoTimeout(soTimeout);
  return sslsock;
}
 

Example 48

From project be.norio.twunch.android, under directory /src/be/norio/twunch/android/util/.

Source file: ViewServer.java

  29 
vote

/** 
 * Starts the server.
 * @return True if the server was successfully created, or false if italready exists.
 * @throws IOException If the server cannot be created.
 * @see #stop()
 * @see #isRunning()
 * @see WindowManagerService#startViewServer(int)
 */
public boolean start() throws IOException {
  if (mThread != null) {
    return false;
  }
  mServer=new ServerSocket(mPort,VIEW_SERVER_MAX_CONNECTIONS,InetAddress.getByAddress(new byte[]{127,0,0,1}));
  mThread=new Thread(this,"Local View Server [port=" + mPort + "]");
  mThreadPool=Executors.newFixedThreadPool(VIEW_SERVER_MAX_CONNECTIONS);
  mThread.start();
  return true;
}
 

Example 49

From project Cafe, under directory /testservice/src/com/baidu/cafe/remote/.

Source file: Client.java

  29 
vote

/** 
 * @param serverIP IP of the server which client talks with
 */
public Client(String serverIP){
  boolean isReachable=false;
  try {
    isReachable=InetAddress.getByName(serverIP).isReachable(TIMEOUT);
  }
 catch (  UnknownHostException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
 finally {
    if (isReachable) {
      mServerIP=serverIP;
      Log.d("Client",serverIP + " is reachable!");
    }
  }
}
 

Example 50

From project Carnivore, under directory /org/rsg/carnivore/net/.

Source file: IPAddress.java

  29 
vote

/** 
 * Constructor
 * @param s IP address in format 123.45.67.89
 */
public IPAddress(String s){
  try {
    this.ip=InetAddress.getByName(s);
  }
 catch (  UnknownHostException e) {
    Log.debug("[" + this.getClass().getName() + "] getByName: "+ e);
  }
}
 

Example 51

From project caseconductor-platform, under directory /utest-domain-services/src/main/java/com/utest/domain/service/util/.

Source file: TrustedSSLUtil.java

  29 
vote

public Socket createSocket(final String host,final int port,final InetAddress localAddress,final int localPort,final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  if (params == null) {
    throw new IllegalArgumentException("Parameters may not be null");
  }
  final int timeout=params.getConnectionTimeout();
  final SocketFactory socketfactory=getSSLContext().getSocketFactory();
  if (timeout == 0) {
    return socketfactory.createSocket(host,port,localAddress,localPort);
  }
 else {
    final Socket socket=socketfactory.createSocket();
    final SocketAddress localaddr=new InetSocketAddress(localAddress,localPort);
    final SocketAddress remoteaddr=new InetSocketAddress(host,port);
    socket.bind(localaddr);
    socket.connect(remoteaddr,timeout);
    return socket;
  }
}
 

Example 52

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/extraction/demux/processor/mapper/.

Source file: ClientTraceProcessor.java

  29 
vote

protected Locality getLocality(String src,String dst) throws Exception {
  if (null == src || null == dst) {
    throw new IOException("Missing src/dst");
  }
  ipMatcher.reset(src);
  if (!ipMatcher.find()) {
    throw new IOException("Could not find src");
  }
  byte[] srcIP=InetAddress.getByName(ipMatcher.group(0)).getAddress();
  ipMatcher.reset(dst);
  if (!ipMatcher.find()) {
    throw new IOException("Could not find dst");
  }
  byte[] dstIP=InetAddress.getByName(ipMatcher.group(0)).getAddress();
  for (int i=0; i < 4; ++i) {
    if (srcIP[i] != dstIP[i]) {
      return (3 == i && (srcIP[i] & 0xC0) == (dstIP[i] & 0xC0)) ? Locality.INTRA : Locality.INTER;
    }
  }
  return Locality.LOCAL;
}
 

Example 53

From project cipango, under directory /cipango-server/src/main/java/org/cipango/server/.

Source file: AbstractSipConnector.java

  29 
vote

@Override protected void doStart() throws Exception {
  if (_port <= 0)   _port=getTransport().getDefaultPort();
  if (_host == null) {
    try {
      _host=InetAddress.getLocalHost().getHostAddress();
    }
 catch (    Exception e) {
      LOG.ignore(e);
      _host="127.0.0.1";
    }
  }
  _uri=new SipURIImpl(_host,_port);
  super.doStart();
  open();
synchronized (this) {
    for (int i=0; i < _acceptors.length; i++)     getExecutor().execute(new Acceptor(i));
  }
  LOG.info("Started {}",this);
}
 

Example 54

From project CIShell, under directory /clients/remoting/org.cishell.reference.remoting/src/org/cishell/reference/remoting/server/.

Source file: CIShellFrameworkServer.java

  29 
vote

public CIShellFrameworkServer(BundleContext bContext,CIShellContext ciContext){
  this.bContext=bContext;
  q=new EventQueue(bContext);
  String host="localhost";
  try {
    host=InetAddress.getLocalHost().getHostName();
  }
 catch (  UnknownHostException e) {
  }
  listeners=new ObjectRegistry(host + ":8180-");
  eventAdmin=(EventAdmin)bContext.getService(bContext.getServiceReference(EventAdmin.class.getName()));
}
 

Example 55

From project Cloud9, under directory /src/dist/edu/umd/cloud9/collection/.

Source file: DocumentForwardIndexHttpServer.java

  29 
vote

public void run(JobConf conf,Reporter reporter) throws IOException {
  int port=8888;
  String indexFile=conf.get("IndexFile");
  String mappingFile=conf.get("DocnoMappingDataFile");
  Path tmpPath=new Path(conf.get("TmpPath"));
  String host=InetAddress.getLocalHost().toString();
  sLogger.info("host: " + host);
  sLogger.info("port: " + port);
  sLogger.info("forward index: " + indexFile);
  FileSystem fs=FileSystem.get(conf);
  FSDataInputStream in=fs.open(new Path(indexFile));
  String indexClass=in.readUTF();
  in.close();
  sLogger.info("index class: " + indexClass);
  try {
    sForwardIndex=(DocumentForwardIndex<Indexable>)Class.forName(indexClass).newInstance();
    sForwardIndex.loadIndex(new Path(indexFile),new Path(mappingFile),fs);
  }
 catch (  Exception e) {
    e.printStackTrace();
    throw new RuntimeException("Error initializing forward index!");
  }
  Server server=new Server(port);
  Context root=new Context(server,"/",Context.SESSIONS);
  root.addServlet(new ServletHolder(new FetchDocidServlet()),"/fetch_docid");
  root.addServlet(new ServletHolder(new FetchDocnoServlet()),"/fetch_docno");
  root.addServlet(new ServletHolder(new HomeServlet()),"/");
  FSDataOutputStream out=FileSystem.get(conf).create(tmpPath,true);
  out.writeUTF(host);
  out.close();
  try {
    server.start();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  while (true)   ;
}
 

Example 56

From project cloudbees-api-client, under directory /cloudbees-api-client/src/test/java/com/cloudbees/api/util/.

Source file: ProxyServer.java

  29 
vote

private Connector getDefaultConnector(String hostName,int port){
  Connector connector=new SocketConnector();
  if (hostName != null) {
    connector.setHost(hostName);
  }
 else {
    try {
      connector.setHost(InetAddress.getLocalHost().getCanonicalHostName());
    }
 catch (    UnknownHostException e) {
    }
  }
  if (port > 0) {
    connector.setPort(port);
  }
  return connector;
}
 

Example 57

From project cmsandroid, under directory /src/com/zia/freshdocs/net/.

Source file: EasySSLSocketFactory.java

  29 
vote

/** 
 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,java.lang.String,int,java.net.InetAddress,int,org.apache.http.params.HttpParams)
 */
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 sslsock=(SSLSocket)((sock != null) ? sock : createSocket());
  if ((localAddress != null) || (localPort > 0)) {
    if (localPort < 0) {
      localPort=0;
    }
    InetSocketAddress isa=new InetSocketAddress(localAddress,localPort);
    sslsock.bind(isa);
  }
  sslsock.connect(remoteAddress,connTimeout);
  sslsock.setSoTimeout(soTimeout);
  return sslsock;
}
 

Example 58

From project commandbook, under directory /src/main/java/com/sk89q/commandbook/bans/.

Source file: CSVBanDatabase.java

  29 
vote

public boolean isBannedAddress(InetAddress address){
  Ban ban=ipBan.get(address.getHostAddress());
  if (ban != null) {
    if (ban.getEnd() != 0L && ban.getEnd() - System.currentTimeMillis() <= 0) {
      unban(null,address.getHostAddress(),null,"Tempban expired");
      save();
      return false;
    }
    return true;
  }
  return false;
}
 

Example 59

From project components-ness-jmx, under directory /src/main/java/com/nesscomputing/jmx/starter/guice/.

Source file: JmxExporterConfigProvider.java

  29 
vote

@Inject(optional=true) void injectGalaxyConfig(final GalaxyConfig galaxyConfig) throws IOException {
  this.galaxyPort=galaxyConfig.getPrivate().getPortJmx() == 0 ? null : galaxyConfig.getPrivate().getPortJmx();
  final String host=galaxyConfig.getInternalIp().getIp();
  if (host != null) {
    this.galaxyHost=InetAddress.getByName(host);
  }
}