InetAddress(IP地址相关类)
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Example01 {
public static void main(String[] args) throws IOException {
InetAddress localAdress = InetAddress.getLocalHost();
InetAddress remoteAddress = InetAddress.getByName("www.itcast.cn");
System.out.println("本机的IP地址"+localAdress.getHostAddress());
System.out.println("itcast"+remoteAddress.getHostAddress());
System.out.println(remoteAddress.isReachable(3000));
System.out.println(remoteAddress.getHostName());
}
}
Tcp网络程序
package one;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
new TCPClient().connect();
}
}
class TCPClient{
private static final int Port=2222;
public void connect()throws Exception{
Socket client =new Socket(InetAddress.getLocalHost(),Port);
java.io.InputStream is =client.getInputStream();
byte[]buf=new byte[1024];
int len =is.read(buf);
System.out.println(new String(buf,0,len));
client.close();
}
}
package one;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
new TCPServer().listen();
}
}
class TCPServer{
private static final int PORT= 2222;
public void listen()throws Exception{
ServerSocket serverSocket =new ServerSocket(PORT);
Socket client =serverSocket.accept();
OutputStream os =client.getOutputStream();
System.out.println("开始于客户端交换数据");
os.write(("传智播客!").getBytes());
Thread.sleep(5000);
System.out.println("结束与客户端交互数据");
client.close();
}
}