1 /*
2 * Copyright 2017 The Netty Project
3 *
4 * The Netty Project licenses this file to you under the Apache License,
5 * version 2.0 (the "License"); you may not use this file except in compliance
6 * with the License. You may obtain a copy of the License at:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16 package io.netty.channel.epoll;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.util.internal.PlatformDependent;
20
21 import java.net.InetAddress;
22 import java.net.InetSocketAddress;
23 import java.net.UnknownHostException;
24
25 public final class UnixChannelUtil {
26
27 private UnixChannelUtil() {
28 }
29
30 /**
31 * Checks if the specified buffer has memory address or is composed of n(n <= IOV_MAX) NIO direct buffers.
32 * (We check this because otherwise we need to make it a new direct buffer.)
33 */
34 public static boolean isBufferCopyNeededForWrite(ByteBuf byteBuf) {
35 return isBufferCopyNeededForWrite(byteBuf, Native.IOV_MAX);
36 }
37
38 static boolean isBufferCopyNeededForWrite(ByteBuf byteBuf, int iovMax) {
39 return !byteBuf.hasMemoryAddress() && (!byteBuf.isDirect() || byteBuf.nioBufferCount() > iovMax);
40 }
41
42 public static InetSocketAddress computeRemoteAddr(InetSocketAddress remoteAddr, InetSocketAddress osRemoteAddr) {
43 if (osRemoteAddr != null) {
44 if (PlatformDependent.javaVersion() >= 7) {
45 try {
46 // Only try to construct a new InetSocketAddress if we using java >= 7 as getHostString() does not
47 // exists in earlier releases and so the retrieval of the hostname could block the EventLoop if a
48 // reverse lookup would be needed.
49 return new InetSocketAddress(InetAddress.getByAddress(remoteAddr.getHostString(),
50 osRemoteAddr.getAddress().getAddress()),
51 osRemoteAddr.getPort());
52 } catch (UnknownHostException ignore) {
53 // Should never happen but fallback to osRemoteAddr anyway.
54 }
55 }
56 return osRemoteAddr;
57 }
58 return remoteAddr;
59 }
60 }