socket编程之---------获取客户端主机名和IP地址

TCP 服务器端:

package com.wodwl.example;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class GetSocketInfo {
 public static void main(String[] args) {
  try {
   ServerSocket server = new ServerSocket(79);
   while (true) {
    System.out.println(“Connection……”);
    Socket socket = server.accept();
    InetAddress addr = socket.getInetAddress();
    System.out.println(“Connection from==>” + addr.getHostName()
      + “/t” + addr.getHostAddress());
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

}

TCP客户端:

package com.wodwl.example;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class ClientSocket {
 public static void main(String[] args) throws IOException {
  InetAddress addr=InetAddress.getByName(“localhost”);
  Socket socket=new Socket(addr,79);
  socket.close();
 }
}

 

运行结果:

Connection……
Connection from==>localhost     127.0.0.1
Connection……

    原文作者:时海
    原文地址: https://blog.csdn.net/wodwl/article/details/4408844
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞