示例#1
0
 public InetSocketAddress getLocalAddress() throws IOException {
   if (!nfd.isValid()) return null;
   ByteBuffer name = ByteBuffer.allocateDirect(18);
   int namelen = getsockname(nfd.getNativeFD(), name);
   if (namelen == 0) // not bound
   return null; // XXX return some wildcard?
   if (namelen == 4) {
     byte[] addr = new byte[4];
     name.get(addr);
     int port = name.getShort() & 0xFFFF;
     return new InetSocketAddress(Inet4Address.getByAddress(addr), port);
   }
   if (namelen == 16) {
     byte[] addr = new byte[16];
     name.get(addr);
     int port = name.getShort() & 0xFFFF;
     return new InetSocketAddress(Inet6Address.getByAddress(addr), port);
   }
   throw new SocketException("invalid address length");
 }
示例#2
0
 /**
  * Returns the socket address of the remote peer this channel is connected to, or null if this
  * channel is not yet connected.
  *
  * @return The peer address.
  * @throws IOException
  */
 public InetSocketAddress getPeerAddress() throws IOException {
   if (!nfd.isValid()) return null;
   ByteBuffer name = ByteBuffer.allocateDirect(18);
   int namelen = getpeername(nfd.getNativeFD(), name);
   if (namelen == 0) // not connected yet
   return null;
   if (namelen == 4) // IPv4
   {
     byte[] addr = new byte[4];
     name.get(addr);
     int port = name.getShort() & 0xFFFF;
     return new InetSocketAddress(Inet4Address.getByAddress(addr), port);
   } else if (namelen == 16) // IPv6
   {
     byte[] addr = new byte[16];
     name.get(addr);
     int port = name.getShort() & 0xFFFF;
     return new InetSocketAddress(Inet6Address.getByAddress(addr), port);
   }
   throw new SocketException("invalid address length");
 }
示例#3
0
 /**
  * Open a file at PATH, initializing the native state to operate on that open file.
  *
  * @param path The absolute file path.
  * @throws IOException If the file cannot be opened, or if this channel was previously
  *     initialized.
  */
 public void openFile(String path, int mode) throws IOException {
   if (nfd.isValid() || nfd.isClosed()) throw new IOException("can't reinitialize this channel");
   int fd = open(path, mode);
   nfd.setNativeFD(fd);
   kind = Kind.FILE;
 }
示例#4
0
 /**
  * Create a new socket. This method will initialize the native file descriptor state of this
  * instance.
  *
  * @param stream Whether or not to create a streaming socket, or a datagram socket.
  * @throws IOException If creating a new socket fails, or if this channel already has its native
  *     descriptor initialized.
  */
 public void initSocket(boolean stream) throws IOException {
   if (nfd.isValid()) throw new IOException("native FD already initialized");
   if (stream) kind = Kind.SOCK_STREAM;
   else kind = Kind.SOCK_DGRAM;
   nfd.setNativeFD(socket(stream));
 }