View Javadoc
1   /*
2    * Copyright 2012 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.socket;
17  
18  import io.netty.util.NetUtil;
19  
20  import java.net.Inet4Address;
21  import java.net.Inet6Address;
22  import java.net.InetAddress;
23  
24  /**
25   * Internet Protocol (IP) families used byte the {@link DatagramChannel}
26   */
27  public enum InternetProtocolFamily {
28      IPv4(Inet4Address.class, 1),
29      IPv6(Inet6Address.class, 2);
30  
31      private final Class<? extends InetAddress> addressType;
32      private final int addressNumber;
33  
34      InternetProtocolFamily(Class<? extends InetAddress> addressType, int addressNumber) {
35          this.addressType = addressType;
36          this.addressNumber = addressNumber;
37      }
38  
39      /**
40       * Returns the address type of this protocol family.
41       */
42      public Class<? extends InetAddress> addressType() {
43          return addressType;
44      }
45  
46      /**
47       * Returns the
48       * <a href="https://www.iana.org/assignments/address-family-numbers/address-family-numbers.xhtml">address number</a>
49       * of the family.
50       */
51      public int addressNumber() {
52          return addressNumber;
53      }
54  
55      /**
56       * Returns the {@link InetAddress} that represent the {@code LOCALHOST} for the family.
57       */
58      public InetAddress localhost() {
59          switch (this) {
60              case IPv4:
61                  return NetUtil.LOCALHOST4;
62              case IPv6:
63                  return NetUtil.LOCALHOST6;
64              default:
65                  throw new IllegalStateException("Unsupported family " + this);
66          }
67      }
68  
69      /**
70       * Returns the {@link InternetProtocolFamily} for the given {@link InetAddress}.
71       */
72      public static InternetProtocolFamily of(InetAddress address) {
73          if (address instanceof Inet4Address) {
74              return IPv4;
75          }
76          if (address instanceof Inet6Address) {
77              return IPv6;
78          }
79          throw new IllegalArgumentException("address " + address + " not supported");
80      }
81  }