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    *   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.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, NetUtil.LOCALHOST4),
29      IPv6(Inet6Address.class, 2, NetUtil.LOCALHOST6);
30  
31      private final Class<? extends InetAddress> addressType;
32      private final int addressNumber;
33      private final InetAddress localHost;
34  
35      InternetProtocolFamily(Class<? extends InetAddress> addressType, int addressNumber, InetAddress localHost) {
36          this.addressType = addressType;
37          this.addressNumber = addressNumber;
38          this.localHost = localHost;
39      }
40  
41      /**
42       * Returns the address type of this protocol family.
43       */
44      public Class<? extends InetAddress> addressType() {
45          return addressType;
46      }
47  
48      /**
49       * Returns the
50       * <a href="http://www.iana.org/assignments/address-family-numbers/address-family-numbers.xhtml">address number</a>
51       * of the family.
52       */
53      public int addressNumber() {
54          return addressNumber;
55      }
56  
57      /**
58       * Returns the {@link InetAddress} that represent the {@code LOCALHOST} for the family.
59       */
60      public InetAddress localhost() {
61          return localHost;
62      }
63  
64      /**
65       * Returns the {@link InternetProtocolFamily} for the given {@link InetAddress}.
66       */
67      public static InternetProtocolFamily of(InetAddress address) {
68          if (address instanceof Inet4Address) {
69              return IPv4;
70          }
71          if (address instanceof Inet6Address) {
72              return IPv6;
73          }
74          throw new IllegalArgumentException("address " + address + " not supported");
75      }
76  }