title: How to fix getsockname failed: EBADF (Bad file number)?
body: <p>My application does <code>network operations</code>, like <code>socket</code> creation, sending and receiving the <code>TCP</code> packets. Some times i will get this below exception which i was unable to fix. I have tried with all possible fixes but as it is fatal exception my application will be crashed and closed which is very annoying.</p>
  
  <p>What are possible things we can make to avoid this issue or atleast can avoid crashing ??</p>
  
  <p>Any helps will be highly appreciated !!</p>
  
  <pre><code>01-24 10:29:27.675: E/AndroidRuntime(3781): java.lang.AssertionError: libcore.io.ErrnoException: getsockname failed: EBADF (Bad file number)
  01-24 10:29:27.675: E/AndroidRuntime(3781):     at libcore.io.IoBridge.getSocketLocalAddress(IoBridge.java:583)
  01-24 10:29:27.675: E/AndroidRuntime(3781):     at java.net.Socket.cacheLocalAddress(Socket.java:950)
  01-24 10:29:27.675: E/AndroidRuntime(3781):     at java.net.Socket.startupSocket(Socket.java:568)
  01-24 10:29:27.675: E/AndroidRuntime(3781):     at java.net.Socket.tryAllAddresses(Socket.java:127)
  01-24 10:29:27.675: E/AndroidRuntime(3781):     at java.net.Socket.&lt;init&gt;(Socket.java:177)
  01-24 10:29:27.675: E/AndroidRuntime(3781):     at java.net.Socket.&lt;init&gt;(Socket.java:149)
  </code></pre>
  
  <p>PS : Here is my sample code :</p>
  
  <pre><code>InetAddress local_inet_addr = null;
      try {
          Socket socket = new Socket("www.xxxxxxx.com", 80);
          if (socket != null) {
              local_inet_addr = socket.getLocalAddress();
              socket.close();
              socket = null;
          }
      } catch (Exception e) {
          try {
              Socket socket = new Socket("www.yyyyyyyy.net", 80);
              if (socket != null) {
                  local_inet_addr = socket.getLocalAddress();
                  socket.close();
                  socket = null;
              }
          } catch (Exception ex) {
          }
      }
  </code></pre>
  
  <p>Here xxxx and yyyy will be my personal domain names.</p>