下面列出了java.net.InetAddress#getLocalHost ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
/**
* <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;
}
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);
}
}
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);
}
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();
}
}
@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);
}
/**
* @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)));
}
public static String getLocalHostName() {
try {
InetAddress addr = InetAddress.getLocalHost();
return addr.getHostName();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 获取当前网络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];
}
/**
* 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;
}
public JKademliaNode(String ownerId, KademliaId defaultId, int udpPort) throws IOException
{
this(
ownerId,
new Node(defaultId, InetAddress.getLocalHost(), udpPort),
udpPort,
new DefaultConfiguration()
);
}
/**
* 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;
}
}
private static InetAddress createLocalAddress() {
try {
return InetAddress.getLocalHost();
} catch (UnknownHostException e) {
LOGGER.warn("Error creating local InetAddress", e);
return null;
}
}
/**
* 获取客户端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;
}
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
}
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;
}
/** 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"));
}
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();
}
/**
* 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;
}
/**
* 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;
}