InetAddress 类
package API_;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Api_demo {
public static void main(String[] args) throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost+"~~~");
InetAddress ByName = InetAddress.getByName("DESKTOP-I7BM4JK");
System.out.println(ByName);
InetAddress byName = InetAddress.getByName("www.xn--zsru59c.top");
System.out.println(byName);
String hostAddress = byName.getHostAddress();
System.out.println(hostAddress);
String hostName = byName.getHostName();
System.out.println(hostName);
}
}
Socket
TCP字节流编程 客户端
package TCP;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCP_client_demo {
public static void main(String[] args) throws IOException {
Socket socket=new Socket(InetAddress.getLocalHost(),9999);
OutputStream os = socket.getOutputStream();
os.write("hello,server".getBytes());
socket.shutdownOutput();
InputStream is = socket.getInputStream();
byte[] by=new byte[1024];
int count;
while ((count=is.read(by))!=-1){
System.out.print(new String(by,0,count));
}
socket.close();
os.close();
}
}
TCP字节流编程 服务端
package TCP;
import com.sun.corba.se.impl.encoding.CDROutputStream_1_0;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCP_server_demo {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(9999);
Socket socket = serverSocket.accept();
InputStream is_ = socket.getInputStream();
byte[] buf=new byte[1024];
int count;
while ((count=is_.read(buf))!=-1){
System.out.print(new String(buf,0,count));
}
OutputStream os_=socket.getOutputStream();
os_.write("hello,client".getBytes());
socket.shutdownOutput();
socket.close();
serverSocket.close();
is_.close();
os_.close();
}
}