com.taobao.metamorphosis.network.RemotingUtils Maven / Gradle / Ivy
/*
* (C) 2007-2012 Alibaba Group Holding Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Authors:
* wuhua , boyan
*/
package com.taobao.metamorphosis.network;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.taobao.gecko.core.command.ResponseCommand;
import com.taobao.gecko.service.Connection;
import com.taobao.gecko.service.exception.NotifyRemotingException;
public class RemotingUtils {
static final Log log = LogFactory.getLog(RemotingUtils.class);
public static void response(final Connection conn, final ResponseCommand response) {
if (response == null || conn == null) {
return;
}
try {
conn.response(response);
}
catch (final NotifyRemotingException e) {
log.error("??????Ӧʧ??", e);
}
}
public static String getLocalAddress() throws Exception {
// ??????????????һ???ǻ?·ip??ַ??????
final Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
InetAddress ipv6Address = null;
while (enumeration.hasMoreElements()) {
final NetworkInterface networkInterface = enumeration.nextElement();
final Enumeration en = networkInterface.getInetAddresses();
while (en.hasMoreElements()) {
final InetAddress address = en.nextElement();
if (!address.isLoopbackAddress()) {
if (address instanceof Inet6Address) {
ipv6Address = address;
}
else {
// ????ʹ??ipv4
return normalizeHostAddress(address);
}
}
}
}
// û??ipv4????ʹ??ipv6
if (ipv6Address != null) {
return normalizeHostAddress(ipv6Address);
}
final InetAddress localHost = InetAddress.getLocalHost();
return normalizeHostAddress(localHost);
}
public static String normalizeHostAddress(final InetAddress localHost) {
if (localHost instanceof Inet6Address) {
return "[" + localHost.getHostAddress() + "]";
}
else {
return localHost.getHostAddress();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy