java.net.Socket.getInetAddress()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(10.0k)|赞(0)|评价(0)|浏览(337)

本文整理了Java中java.net.Socket.getInetAddress()方法的一些代码示例,展示了Socket.getInetAddress()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Socket.getInetAddress()方法的具体详情如下:
包路径:java.net.Socket
类名称:Socket
方法名:getInetAddress

Socket.getInetAddress介绍

[英]Returns the IP address of the target host this socket is connected to, or null if this socket is not yet connected.
[中]返回此套接字连接到的目标主机的IP地址,如果此套接字尚未连接,则返回null。

代码示例

代码示例来源:origin: square/okhttp

private void processHandshakeFailure(Socket raw) throws Exception {
 SSLContext context = SSLContext.getInstance("TLS");
 context.init(null, new TrustManager[] {UNTRUSTED_TRUST_MANAGER}, new SecureRandom());
 SSLSocketFactory sslSocketFactory = context.getSocketFactory();
 SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(
   raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
 try {
  socket.startHandshake(); // we're testing a handshake failure
  throw new AssertionError();
 } catch (IOException expected) {
 }
 socket.close();
}

代码示例来源:origin: aws/aws-sdk-java

/**
 * Returns the endpoint in the format of "address:port"
 */
private String endpoint() {
  return sock.getInetAddress() + ":" + sock.getPort();
}

代码示例来源:origin: igniterealtime/Openfire

@Override
public String getHostAddress() throws UnknownHostException {
  return socket.getInetAddress().getHostAddress();
}

代码示例来源:origin: org.codehaus.groovy/groovy

GroovyClientConnection(Script script, boolean autoOutput,Socket socket) throws IOException {
  this.script = script;
  this.autoOutputFlag = autoOutput;
  this.socket = socket;
  reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  writer = new PrintWriter(socket.getOutputStream());
  new Thread(this, "Groovy client connection - " + socket.getInetAddress().getHostAddress()).start();
}
public void run() {

代码示例来源:origin: redisson/redisson

final void process(Socket clnt) throws IOException {
  InputStream in = new BufferedInputStream(clnt.getInputStream());
  String cmd = readLine(in);
  logging(clnt.getInetAddress().getHostName(),
      new Date().toString(), cmd);
  while (skipLine(in) > 0){
  }
  OutputStream out = new BufferedOutputStream(clnt.getOutputStream());
  try {
    doReply(in, out, cmd);
  }
  catch (BadHttpRequest e) {
    replyError(out, e);
  }
  out.flush();
  in.close();
  out.close();
  clnt.close();
}

代码示例来源:origin: plantuml/plantuml

public void go() throws IOException {
  final ServerSocket s = new ServerSocket(listenPort);
  final ExecutorService exe = Executors.newCachedThreadPool();
  while (true) {
    final Socket incoming = s.accept();
    ip = incoming.getLocalAddress().getHostAddress();
    System.out.println("New Client Connected from " + incoming.getInetAddress().getHostName() + "... ");
    exe.submit(new FtpLoop(incoming, this));
  }
}

代码示例来源:origin: smuyyh/BookReader

do {
  try {
    final Socket finalAccept = myServerSocket.accept();
    Log.i("NanoHTTPD",
        "accept request from "
            + finalAccept.getInetAddress());
    InputStream inputStream = finalAccept.getInputStream();
    OutputStream outputStream = finalAccept
        .getOutputStream();
    TempFileManager tempFileManager = tempFileManagerFactory
        .create();

代码示例来源:origin: log4j/log4j

Socket socket = null;
try {
 socket = serverSocket.accept();
  InetAddress remoteAddress = socket.getInetAddress();
  LogLog.debug("accepting connection from " + remoteAddress.getHostName() 
   + " (" + remoteAddress.getHostAddress() + ")");
  ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
  if (buffer != null && buffer.length() > 0) {
   sendCachedEvents(oos);

代码示例来源:origin: commons-net/commons-net

InputStream _createErrorStream() throws IOException
{
  ServerSocket server;
  Socket socket;
  server = _serverSocketFactory_.createServerSocket(0, 1, getLocalAddress());
  _output_.write(Integer.toString(server.getLocalPort()).getBytes("UTF-8")); // $NON-NLS-1$
  _output_.write(NULL_CHAR);
  _output_.flush();
  socket = server.accept();
  server.close();
  if (__remoteVerificationEnabled && !verifyRemote(socket))
  {
    socket.close();
    throw new IOException(
      "Security violation: unexpected connection attempt by " +
      socket.getInetAddress().getHostAddress());
  }
  return (new SocketInputStream(socket, socket.getInputStream()));
}

代码示例来源:origin: log4j/log4j

/** Listens for client connections **/
  public void run() {
    LOG.info("Thread started");
    try {
      while (true) {
        LOG.debug("Waiting for a connection");
        final Socket client = mSvrSock.accept();
        LOG.debug("Got a connection from " +
             client.getInetAddress().getHostName());
        final Thread t = new Thread(new Slurper(client));
        t.setDaemon(true);
        t.start();
      }
    } catch (IOException e) {
      LOG.error("Error in accepting connections, stopping.", e);
    }
  }
}

代码示例来源:origin: apache/hbase

@Override
 public Socket accept() throws IOException {
  Socket socket = super.accept();
  SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
  SSLSocket sslSocket =
    (SSLSocket) sslSocketFactory.createSocket(socket,
     socket.getInetAddress().getHostName(), socket.getPort(), true);
  sslSocket.setUseClientMode(false);
  sslSocket.setNeedClientAuth(false);
  ArrayList<String> secureProtocols = new ArrayList<>();
  for (String p : sslSocket.getEnabledProtocols()) {
   if (!p.contains("SSLv3")) {
    secureProtocols.add(p);
   }
  }
  sslSocket.setEnabledProtocols(secureProtocols.toArray(new String[secureProtocols.size()]));
  return sslSocket;
 }
};

代码示例来源:origin: NanoHttpd/nanohttpd

@Override
  public void run() {
    OutputStream outputStream = null;
    try {
      outputStream = this.acceptSocket.getOutputStream();
      ITempFileManager tempFileManager = httpd.getTempFileManagerFactory().create();
      HTTPSession session = new HTTPSession(httpd, tempFileManager, this.inputStream, outputStream, this.acceptSocket.getInetAddress());
      while (!this.acceptSocket.isClosed()) {
        session.execute();
      }
    } catch (Exception e) {
      // When the socket is closed by the client,
      // we throw our own SocketException
      // to break the "keep alive" loop above. If
      // the exception was anything other
      // than the expected SocketException OR a
      // SocketTimeoutException, print the
      // stacktrace
      if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) {
        NanoHTTPD.LOG.log(Level.SEVERE, "Communication with the client broken, or an bug in the handler code", e);
      }
    } finally {
      NanoHTTPD.safeClose(outputStream);
      NanoHTTPD.safeClose(this.inputStream);
      NanoHTTPD.safeClose(this.acceptSocket);
      httpd.asyncRunner.closed(this);
    }
  }
}

代码示例来源:origin: spring-projects/spring-integration

InputStream is = mock(InputStream.class);
when(is.read()).thenReturn(-1);
when(socket.getInputStream()).thenReturn(is);
InetAddress inetAddress = InetAddress.getLocalHost();
when(socket.getInetAddress()).thenReturn(inetAddress);
ServerSocket serverSocket = mock(ServerSocket.class);
when(serverSocket.getInetAddress()).thenReturn(inetAddress);
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
when(serverSocket.accept()).thenReturn(socket).then(invocation -> {
  latch1.countDown();
  latch2.await(10, TimeUnit.SECONDS);

代码示例来源:origin: apache/geode

private ServerConnection serverConnectionMockedExceptForCommunicationMode(byte communicationMode)
  throws IOException {
 Socket socketMock = mock(Socket.class);
 when(socketMock.getInetAddress()).thenReturn(InetAddress.getByName("localhost"));
 InputStream streamMock = mock(InputStream.class);
 when(streamMock.read()).thenReturn(1);
 when(socketMock.getInputStream()).thenReturn(streamMock);
 return new ServerConnectionFactory().makeServerConnection(socketMock, mock(InternalCache.class),
   mock(CachedRegionHelper.class), mock(CacheServerStats.class), 0, 0, "", communicationMode,
   mock(AcceptorImpl.class), mock(SecurityService.class));
}

代码示例来源:origin: jenkinsci/jenkins

Writer o = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
  o.write("Jenkins-Version: " + Jenkins.VERSION + "\r\n");
  o.write("Jenkins-Session: " + Jenkins.SESSION_HASH + "\r\n");
  o.write("Client: " + s.getInetAddress().getHostAddress() + "\r\n");
  o.write("Server: " + s.getLocalAddress().getHostAddress() + "\r\n");
  o.write("Remoting-Minimum-Version: " + RemotingVersionInfo.getMinimumSupportedVersion() + "\r\n");
  o.flush();
InputStream i = s.getInputStream();
IOUtils.copy(i, new NullOutputStream());
s.shutdownInput();

代码示例来源:origin: wildfly/wildfly

protected String getSockAddress() {
  StringBuilder sb=new StringBuilder();
  if(sock != null) {
    sb.append(sock.getLocalAddress().getHostAddress()).append(':').append(sock.getLocalPort());
    sb.append(" - ").append(sock.getInetAddress().getHostAddress()).append(':').append(sock.getPort());
  }
  return sb.toString();
}

代码示例来源:origin: apache/nifi

@Override
public void receiveFlowFiles(final Socket socket) throws IOException {
  final InputStream in = new BufferedInputStream(socket.getInputStream());
  final OutputStream out = new BufferedOutputStream(socket.getOutputStream());
  String peerDescription = socket.getInetAddress().getHostName();
  if (socket instanceof SSLSocket) {
    logger.debug("Connection received from peer {}", peerDescription);
    peerDescription = authorizer.authorize((SSLSocket) socket);
    logger.debug("Client Identities are authorized to load balance data for peer {}", peerDescription);
  }
  final int version = negotiateProtocolVersion(in, out, peerDescription);
  if (version == SOCKET_CLOSED) {
    socket.close();
    return;
  }
  if (version == NO_DATA_AVAILABLE) {
    logger.debug("No data is available from {}", socket.getRemoteSocketAddress());
    return;
  }
  receiveFlowFiles(in, out, peerDescription, version);
}

代码示例来源:origin: apache/geode

public String getSocketHost() {
 return this._socket.getInetAddress().getHostAddress();
}

代码示例来源:origin: marytts/marytts

public void run() {
  logger.info("Starting server.");
  try {
    server = new ServerSocket(MaryProperties.needInteger("socket.port"));
    while (true) {
      logger.info("Waiting for client to connect on port " + server.getLocalPort());
      Socket client = server.accept();
      logger.info("Connection from " + client.getInetAddress().getHostName() + " ("
          + client.getInetAddress().getHostAddress() + ").");
      clients.execute(new ClientHandler(client));
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: stackoverflow.com

connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");

相关文章