java.net.InetAddress#getLocalHost ( )源码实例Demo

下面列出了java.net.InetAddress#getLocalHost ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hottub   文件: SocksConnectTimeout.java
public static void main(String[] args) {
    try {
        serverSocket = new ServerSocket(0);

        (new Thread() {
            @Override
            public void run() { serve(); }
        }).start();

        Proxy socksProxy = new Proxy(Proxy.Type.SOCKS,
            new InetSocketAddress(InetAddress.getLocalHost(), serverSocket.getLocalPort()));

        test(socksProxy);
    } catch (IOException e) {
        unexpected(e);
    } finally {
        close(serverSocket);

        if (failed > 0)
            throw new RuntimeException("Test Failed: passed:" + passed + ", failed:" + failed);
    }
}
 
源代码2 项目: sophia_scaffolding   文件: IdWorker.java
/**
 * <p>
 * 数据标识id部分
 * </p>
 */
protected static long getDatacenterId(long maxDatacenterId) {
    long id = 0L;
    try {
        InetAddress ip = InetAddress.getLocalHost();
        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        if (network == null) {
            id = 1L;
        } else {
            byte[] mac = network.getHardwareAddress();
            id = ((0x000000FF & (long) mac[mac.length - 1])
                    | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
            id = id % (maxDatacenterId + 1);
        }
    } catch (Exception e) {
        System.out.println(" getDatacenterId: " + e.getMessage());
    }
    return id;
}
 
源代码3 项目: jdk8u_jdk   文件: SocksConnectTimeout.java
public static void main(String[] args) {
    try {
        serverSocket = new ServerSocket(0);

        (new Thread() {
            @Override
            public void run() { serve(); }
        }).start();

        Proxy socksProxy = new Proxy(Proxy.Type.SOCKS,
            new InetSocketAddress(InetAddress.getLocalHost(), serverSocket.getLocalPort()));

        test(socksProxy);
    } catch (IOException e) {
        unexpected(e);
    } finally {
        close(serverSocket);

        if (failed > 0)
            throw new RuntimeException("Test Failed: passed:" + passed + ", failed:" + failed);
    }
}
 
源代码4 项目: hadoop   文件: TestFavoredNodesEndToEnd.java
private InetSocketAddress getArbitraryLocalHostAddr() 
    throws UnknownHostException{
  Random rand = new Random(System.currentTimeMillis());
  int port = rand.nextInt(65535);
  while (true) {
    boolean conflict = false;
    for (DataNode d : datanodes) {
      if (d.getXferAddress().getPort() == port) {
        port = rand.nextInt(65535);
        conflict = true;
      }
    }
    if (conflict == false) {
      break;
    }
  }
  return new InetSocketAddress(InetAddress.getLocalHost(), port);
}
 
源代码5 项目: MiniWeChat-Server   文件: Server111.java
public Server111(){
	// 显示IP地址
			InetAddress addr;
			try {
				addr = InetAddress.getLocalHost();
				Debug.log("IP address:" + addr.getHostAddress().toString());
				Debug.log("Host Name:" + addr.getHostName().toString());
				// logger.debug("IP地址:"+addr.getHostAddress().toString());
				// logger.debug("本机名称:"+ addr.getHostName().toString());

			} catch (UnknownHostException e1) {
				e1.printStackTrace();
			}
			Debug.log("Port Number:8081");
			// logger.debug("端口号:8081");

			acceptor = new NioSocketAcceptor();
			// 指定编码解码器
			acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaEncoder(), new MinaDecoder()));
			acceptor.setHandler(this);
			try {
				acceptor.bind(new InetSocketAddress(8081));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
}
 
源代码6 项目: Kylin   文件: CubingJob.java
@Override
protected Pair<String, String> formatNotifications(ExecutableState state) {
    final Output output = jobService.getOutput(getId());
    String logMsg;
    switch (output.getState()) {
        case ERROR:
            logMsg = output.getVerboseMsg();
            break;
        case DISCARDED:
            logMsg = "";
            break;
        case SUCCEED:
            logMsg = "";
            break;
        default:
            return null;
    }
    String content = ExecutableConstants.NOTIFY_EMAIL_TEMPLATE;
    content = content.replaceAll("\\$\\{job_name\\}", getName());
    content = content.replaceAll("\\$\\{result\\}", state.toString());
    content = content.replaceAll("\\$\\{cube_name\\}", getCubeName());
    content = content.replaceAll("\\$\\{start_time\\}", new Date(getStartTime()).toString());
    content = content.replaceAll("\\$\\{duration\\}", getDuration() / 60000 + "mins");
    content = content.replaceAll("\\$\\{mr_waiting\\}", getMapReduceWaitTime() / 60000 + "mins");
    content = content.replaceAll("\\$\\{last_update_time\\}", new Date(getLastModified()).toString());
    content = content.replaceAll("\\$\\{submitter\\}", getSubmitter());
    content = content.replaceAll("\\$\\{error_log\\}", logMsg);

    try {
        InetAddress inetAddress = InetAddress.getLocalHost();
        content = content.replaceAll("\\$\\{job_engine\\}", inetAddress.getCanonicalHostName());
    } catch (UnknownHostException e) {
        logger.warn(e.getLocalizedMessage(), e);
    }

    String title = "["+ state.toString() + "] - [Kylin Cube Build Job]-" + getCubeName();
    return Pair.of(title, content);
}
 
源代码7 项目: myrrix-recommender   文件: PartitionsUtils.java
/**
 * @param port port the instance is configured to run on
 * @return a simple structure representing one partition, one replica: the local host
 *  and configured instance port
 */
public static List<List<HostAndPort>> getDefaultLocalPartition(int port) {
  InetAddress localhost;
  try {
    localhost = InetAddress.getLocalHost();
  } catch (UnknownHostException e) {
    throw new IllegalStateException(e);
  }
  String host = localhost.getHostName();
  return Collections.singletonList(Collections.singletonList(HostAndPort.fromParts(host, port)));
}
 
源代码8 项目: radar   文件: IPUtil.java
public static String getLocalHostName() {
	try {
		InetAddress addr = InetAddress.getLocalHost();
		return addr.getHostName();
	} catch (Exception e) {
		e.printStackTrace();
		return "";
	}
}
 
源代码9 项目: seezoon-framework-all   文件: IpUtils.java
/**
 * 获取当前网络ip
 * 
 * @param request
 * @return
 */
public static String getIpAddr(HttpServletRequest request) {
	String 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") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
			// 根据网卡取本机配置的IP
			InetAddress inet = null;
			try {
				//mac 这里不设置为非常慢
				//scutil --set HostName "localhost"
				inet = InetAddress.getLocalHost();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
			ipAddress = inet.getHostAddress();
		}
	}
	// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
	String[] ips = StringUtils.split(ipAddress,",");
	return ips[0];
}
 
源代码10 项目: jdk8u60   文件: Utils.java
/**
 * Returns the name of the local host.
 *
 * @return The host name
 * @throws UnknownHostException if IP address of a host could not be determined
 */
public static String getHostname() throws UnknownHostException {
    InetAddress inetAddress = InetAddress.getLocalHost();
    String hostName = inetAddress.getHostName();

    assertTrue((hostName != null && !hostName.isEmpty()),
            "Cannot get hostname");

    return hostName;
}
 
源代码11 项目: Kademlia   文件: JKademliaNode.java
public JKademliaNode(String ownerId, KademliaId defaultId, int udpPort) throws IOException
{
    this(
            ownerId,
            new Node(defaultId, InetAddress.getLocalHost(), udpPort),
            udpPort,
            new DefaultConfiguration()
    );
}
 
源代码12 项目: logging-log4j2   文件: NetUtils.java
/**
 * This method gets the network name of the machine we are running on. Returns "UNKNOWN_LOCALHOST" in the unlikely
 * case where the host name cannot be found.
 *
 * @return String the name of the local host
 */
public static String getLocalHostname() {
    try {
        final InetAddress addr = InetAddress.getLocalHost();
        return addr == null ? UNKNOWN_LOCALHOST : addr.getHostName();
    } catch (final UnknownHostException uhe) {
        try {
            final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    final NetworkInterface nic = interfaces.nextElement();
                    final Enumeration<InetAddress> addresses = nic.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        final InetAddress address = addresses.nextElement();
                        if (!address.isLoopbackAddress()) {
                            final String hostname = address.getHostName();
                            if (hostname != null) {
                                return hostname;
                            }
                        }
                    }
                }
            }
        } catch (final SocketException se) {
            LOGGER.error("Could not determine local host name", uhe);
            return UNKNOWN_LOCALHOST;
        }
        LOGGER.error("Could not determine local host name", uhe);
        return UNKNOWN_LOCALHOST;
    }
}
 
源代码13 项目: pinpoint   文件: SocketAddressUtilsTest.java
private static InetAddress createLocalAddress() {
    try {
        return InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        LOGGER.warn("Error creating local InetAddress", e);
        return null;
    }
}
 
源代码14 项目: platform   文件: WebUtils.java
/**
 * 获取客户端IP
 *
 * @param request HttpServletRequest
 * @return String
 */

public static String getHost(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if (Strings.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (Strings.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (Strings.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("X-Real-IP");
    }
    if (Strings.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    if ("127.0.0.1".equals(ip)) {
        InetAddress inet;
        try { // 根据网卡取本机配置的IP
            inet = InetAddress.getLocalHost();
            ip = inet.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
    // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
    if (ip != null && ip.length() > 15) {
        if (ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
        }
    }
    return ip;
}
 
源代码15 项目: jdk8u-dev-jdk   文件: SnmpAdaptorServer.java
private void snmpV1Trap(InetAddress addr,
                        int port,
                        SnmpIpAddress agentAddr,
                        String cs,
                        SnmpOid enterpOid,
                        int generic,
                        int specific,
                        SnmpVarBindList varBindList,
                        SnmpTimeticks time)
    throws IOException, SnmpStatusException {

    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
        SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
            "snmpV1Trap", "generic=" + generic + ", specific=" +
              specific);
    }

    // First, make an SNMP V1 trap pdu
    //
    SnmpPduTrap pdu = new SnmpPduTrap() ;
    pdu.address = null ;
    pdu.port = port ;
    pdu.type = pduV1TrapPdu ;
    pdu.version = snmpVersionOne ;

    //Diff start
    if(cs != null)
        pdu.community = cs.getBytes();
    else
        pdu.community = null ;
    //Diff end

    // Diff start
    if(enterpOid != null)
        pdu.enterprise = enterpOid;
    else
        pdu.enterprise = enterpriseOid ;
    //Diff end
    pdu.genericTrap = generic ;
    pdu.specificTrap = specific ;
    //Diff start
    if(time != null)
        pdu.timeStamp = time.longValue();
    else
        pdu.timeStamp = getSysUpTime();
    //Diff end

    if (varBindList != null) {
        pdu.varBindList = new SnmpVarBind[varBindList.size()] ;
        varBindList.copyInto(pdu.varBindList);
    }
    else
        pdu.varBindList = null ;

    if (agentAddr == null) {
        // If the local host cannot be determined,
        // we put 0.0.0.0 in agentAddr
        try {
            final InetAddress inetAddr =
                (address!=null)?address:InetAddress.getLocalHost();
            agentAddr = handleMultipleIpVersion(inetAddr.getAddress());
        }  catch (UnknownHostException e) {
            byte[] zeroedAddr = new byte[4];
            agentAddr = handleMultipleIpVersion(zeroedAddr);
        }
    }

    pdu.agentAddr = agentAddr;

    // Next, send the pdu to the specified destination
    //
    // Diff start
    if(addr != null)
        sendTrapPdu(addr, pdu) ;
    else
        sendTrapPdu(pdu);

    //End diff
}
 
源代码16 项目: rocketmq   文件: RemotingUtil.java
public static String getLocalAddress() {
    try {
        // Traversal Network interface to get the first non-loopback and non-private address
        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        ArrayList<String> ipv4Result = new ArrayList<String>();
        ArrayList<String> ipv6Result = new ArrayList<String>();
        while (enumeration.hasMoreElements()) {
            final NetworkInterface networkInterface = enumeration.nextElement();
            final Enumeration<InetAddress> en = networkInterface.getInetAddresses();
            while (en.hasMoreElements()) {
                final InetAddress address = en.nextElement();
                if (!address.isLoopbackAddress()) {
                    if (address instanceof Inet6Address) {
                        ipv6Result.add(normalizeHostAddress(address));
                    } else {
                        ipv4Result.add(normalizeHostAddress(address));
                    }
                }
            }
        }

        // prefer ipv4
        if (!ipv4Result.isEmpty()) {
            for (String ip : ipv4Result) {
                if (ip.startsWith("127.0") || ip.startsWith("192.168")) {
                    continue;
                }

                return ip;
            }

            return ipv4Result.get(ipv4Result.size() - 1);
        } else if (!ipv6Result.isEmpty()) {
            return ipv6Result.get(0);
        }
        //If failed to find,fall back to localhost
        final InetAddress localHost = InetAddress.getLocalHost();
        return normalizeHostAddress(localHost);
    } catch (Exception e) {
        log.error("Failed to obtain local address", e);
    }

    return null;
}
 
源代码17 项目: hadoop   文件: TestFsck.java
/** Test fsck with FileNotFound */
@Test
public void testFsckFileNotFound() throws Exception {

  // Number of replicas to actually start
  final short NUM_REPLICAS = 1;

  Configuration conf = new Configuration();
  NameNode namenode = mock(NameNode.class);
  NetworkTopology nettop = mock(NetworkTopology.class);
  Map<String,String[]> pmap = new HashMap<String, String[]>();
  Writer result = new StringWriter();
  PrintWriter out = new PrintWriter(result, true);
  InetAddress remoteAddress = InetAddress.getLocalHost();
  FSNamesystem fsName = mock(FSNamesystem.class);
  BlockManager blockManager = mock(BlockManager.class);
  DatanodeManager dnManager = mock(DatanodeManager.class);

  when(namenode.getNamesystem()).thenReturn(fsName);
  when(fsName.getBlockLocations(any(FSPermissionChecker.class), anyString(),
                                anyLong(), anyLong(),
                                anyBoolean(), anyBoolean()))
      .thenThrow(new FileNotFoundException());
  when(fsName.getBlockManager()).thenReturn(blockManager);
  when(blockManager.getDatanodeManager()).thenReturn(dnManager);

  NamenodeFsck fsck = new NamenodeFsck(conf, namenode, nettop, pmap, out,
      NUM_REPLICAS, remoteAddress);

  String pathString = "/tmp/testFile";

  long length = 123L;
  boolean isDir = false;
  int blockReplication = 1;
  long blockSize = 128 *1024L;
  long modTime = 123123123L;
  long accessTime = 123123120L;
  FsPermission perms = FsPermission.getDefault();
  String owner = "foo";
  String group = "bar";
  byte [] symlink = null;
  byte [] path = new byte[128];
  path = DFSUtil.string2Bytes(pathString);
  long fileId = 312321L;
  int numChildren = 1;
  byte storagePolicy = 0;

  HdfsFileStatus file = new HdfsFileStatus(length, isDir, blockReplication,
      blockSize, modTime, accessTime, perms, owner, group, symlink, path,
      fileId, numChildren, null, storagePolicy);
  Result res = new Result(conf);

  try {
    fsck.check(pathString, file, res);
  } catch (Exception e) {
    fail("Unexpected exception "+ e.getMessage());
  }
  assertTrue(res.toString().contains("HEALTHY"));
}
 
源代码18 项目: hottub   文件: CloseAfterConnect.java
public static void main(String[] args) throws Exception {
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(new InetSocketAddress(0));

    InetAddress lh = InetAddress.getLocalHost();
    final SocketChannel sc = SocketChannel.open();
    final InetSocketAddress isa =
        new InetSocketAddress(lh, ssc.socket().getLocalPort());

    // establish connection in another thread
    Runnable connector =
        new Runnable() {
            public void run() {
                try {
                    sc.connect(isa);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        };
    Thread thr = new Thread(connector);
    thr.start();

    // wait for connect to be established and for thread to
    // terminate
    do {
        try {
            thr.join();
        } catch (InterruptedException x) { }
    } while (thr.isAlive());

    // check connection is established
    if (!sc.isConnected()) {
        throw new RuntimeException("SocketChannel not connected");
    }

    // close channel - this triggered the bug as it attempted to signal
    // a thread that no longer exists
    sc.close();

    // clean-up
    ssc.accept().close();
    ssc.close();
}
 
源代码19 项目: VideoConference   文件: AVTransmit2.java
/**
    * Use the RTPManager API to create sessions for each media 
    * track of the processor.
    */
   private String createTransmitter() {

// Cheated.  Should have checked the type.
PushBufferDataSource pbds = (PushBufferDataSource)dataOutput;
PushBufferStream pbss[] = pbds.getStreams();

rtpMgrs = new RTPManager[pbss.length];
SessionAddress localAddr, destAddr;
InetAddress ipAddr;
SendStream sendStream;
int port;
SourceDescription srcDesList[];

for (int i = 0; i < pbss.length; i++) {
    try {
	rtpMgrs[i] = RTPManager.newInstance();	    

	// The local session address will be created on the
	// same port as the the target port. This is necessary
	// if you use AVTransmit2 in conjunction with JMStudio.
	// JMStudio assumes -  in a unicast session - that the
	// transmitter transmits from the same port it is receiving
	// on and sends RTCP Receiver Reports back to this port of
	// the transmitting host.
	
	port = portBase + 2*i;
	ipAddr = InetAddress.getByName(ipAddress);

	localAddr = new SessionAddress( InetAddress.getLocalHost(),
					port);
	
	destAddr = new SessionAddress( ipAddr, port);

	rtpMgrs[i].initialize( localAddr);
	
	rtpMgrs[i].addTarget( destAddr);
	
	System.err.println( "Created RTP session: " + ipAddress + " " + port);
	
	sendStream = rtpMgrs[i].createSendStream(dataOutput, i);		
	sendStream.start();
    } catch (Exception  e) {
	return e.getMessage();
    }
}

return null;
   }
 
源代码20 项目: balzac   文件: ServerSocketDaemon.java
/**
 * Return a Socket for this daemon. The socket is creating using
 * {@code InetAddress.getLocalHost()} as host.
 * 
 * @return a socket.
 * @throws IOException if an I/O error occurs when creating the socket.
 */
public Socket getSocket() throws IOException {
    Socket socket = new Socket(InetAddress.getLocalHost(), getPort());
    socket.setKeepAlive(true);
    return socket;
}