1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
13   */
14  
15  package com.liferay.portal.kernel.util;
16  
17  import java.io.IOException;
18  
19  import java.net.InetAddress;
20  import java.net.NetworkInterface;
21  import java.net.Socket;
22  
23  /**
24   * <a href="SocketUtil.java.html"><b><i>View Source</i></b></a>
25   *
26   * @author Shuyang Zhou
27   */
28  public class SocketUtil {
29  
30      public static BindInfo getBindInfo(String host, int port)
31          throws IOException {
32  
33          Socket socket = null;
34  
35          try {
36              socket = new Socket(host, port);
37  
38              InetAddress inetAddress = socket.getLocalAddress();
39              NetworkInterface networkInterface =
40                  NetworkInterface.getByInetAddress(inetAddress);
41  
42              BindInfo bindInfo = new BindInfo();
43  
44              bindInfo.setInetAddress(inetAddress);
45              bindInfo.setNetworkInterface(networkInterface);
46  
47              return bindInfo;
48          }
49          finally {
50              if (socket != null) {
51                  try {
52                      socket.close();
53                  }
54                  catch (IOException ioe) {
55                  }
56              }
57          }
58      }
59  
60      public static class BindInfo {
61  
62          public InetAddress getInetAddress() {
63              return _inetAddress;
64          }
65  
66          public NetworkInterface getNetworkInterface() {
67              return _networkInterface;
68          }
69  
70          public void setInetAddress(InetAddress inetAddress) {
71              _inetAddress = inetAddress;
72          }
73  
74          public void setNetworkInterface(NetworkInterface networkInterface) {
75              _networkInterface = networkInterface;
76          }
77  
78          private InetAddress _inetAddress;
79          private NetworkInterface _networkInterface;
80  
81      }
82  
83  }