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.netty5.channel.unix;
17  
18  import io.netty5.buffer.api.Buffer;
19  
20  import java.net.InetAddress;
21  import java.net.InetSocketAddress;
22  import java.net.UnknownHostException;
23  
24  import static io.netty5.channel.unix.Limits.IOV_MAX;
25  
26  public final class UnixChannelUtil {
27  
28      private UnixChannelUtil() {
29      }
30  
31      /**
32       * Checks if the specified buffer has memory address or is composed of n(n <= IOV_MAX) NIO direct buffers.
33       * (We check this because otherwise we need to make it a new direct buffer.)
34       */
35      public static boolean isBufferCopyNeededForWrite(Buffer buffer) {
36          return isBufferCopyNeededForWrite(buffer, IOV_MAX);
37      }
38  
39      static boolean isBufferCopyNeededForWrite(Buffer buffer, int iovMax) {
40          return !buffer.isDirect() || buffer.countReadableComponents() > iovMax;
41      }
42  
43      public static InetSocketAddress computeRemoteAddr(InetSocketAddress remoteAddr, InetSocketAddress osRemoteAddr) {
44          if (osRemoteAddr != null) {
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              return osRemoteAddr;
56          }
57          return remoteAddr;
58      }
59  }