1. 程式人生 > >socket程式設計之---------獲取客戶端主機名和IP地址

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……