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