View Javadoc
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    *   https://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.unix;
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  import static io.netty.channel.unix.Limits.IOV_MAX;
26  
27  public final class UnixChannelUtil {
28  
29      private UnixChannelUtil() {
30      }
31  
32      /**
33       * Checks if the specified buffer has memory address or is composed of n(n <= IOV_MAX) NIO direct buffers.
34       * (We check this because otherwise we need to make it a new direct buffer.)
35       */
36      public static boolean isBufferCopyNeededForWrite(ByteBuf byteBuf) {
37          return isBufferCopyNeededForWrite(byteBuf, IOV_MAX);
38      }
39  
40      static boolean isBufferCopyNeededForWrite(ByteBuf byteBuf, int iovMax) {
41          return !byteBuf.hasMemoryAddress() && (!byteBuf.isDirect() || byteBuf.nioBufferCount() > iovMax);
42      }
43  
44      public static InetSocketAddress computeRemoteAddr(InetSocketAddress remoteAddr, InetSocketAddress osRemoteAddr) {
45          if (osRemoteAddr != null) {
46              if (PlatformDependent.javaVersion() >= 7) {
47                  try {
48                      // Only try to construct a new InetSocketAddress if we using java >= 7 as getHostString() does not
49                      // exists in earlier releases and so the retrieval of the hostname could block the EventLoop if a
50                      // reverse lookup would be needed.
51                      return new InetSocketAddress(InetAddress.getByAddress(remoteAddr.getHostString(),
52                              osRemoteAddr.getAddress().getAddress()),
53                              osRemoteAddr.getPort());
54                  } catch (UnknownHostException ignore) {
55                      // Should never happen but fallback to osRemoteAddr anyway.
56                  }
57              }
58              return osRemoteAddr;
59          }
60          return remoteAddr;
61      }
62  }