IP对应类 : InetAddress类
此类表示互联网协议IP地址
主机名到 IP 地址的解析 通过使用本地机器配置信息和网络命名服务和网络信息服务来实现。
要使用的特定命名服务默认情况下是本地机器配置的那个。
对于任何主机名称,都返回其相应的 IP 地址。
常用方法:
返回本地主机static InetAddress
getLocalHost()
返回此 byte[]
getAddress()InetAddress
对象的原始 IP 地址
getHostName()
获取此 IP 地址的主机名
getHostAddress()
返回 IP 地址字符串
根据提供的主机名和 IP 地址创建 InetAddressstatic InetAddress
getByAddress(String host, byte[] addr)
static InetAddress getByAddress(byte[] addr)
在给定原始 IP 地址的情况下,返回 InetAddress
对象
static InetAddress getAllByName(String host)
在给定主机名的情况下,根据系统上配置的名称服务返回其 IP 地址所组成的数组
例子1:
<strong>public class IPDemo {
public static void main(String[] args) throws UnknownHostException {
// InetAddress i = InetAddress.getLocalHost();
// System.out.println(i.toString());
// System.out.println("Address:"+i.getHostAddress());
// System.out.println("name:"+i.getHostName());
//运行结果:mo/171.39.84.202
// Address:171.39.84.202
// name:mo
// 百度可能有多个主机IP
InetAddress[] i = InetAddress.getAllByName("www.baidu.com");
for (InetAddress ia : i) {
System.out.println("baidu--Address:" + ia.getHostAddress());
System.out.println("baidu--name:" + ia.getHostName());
}
// 运行结果:baidu--Address:112.80.248.74
// baidu--name:www.baidu.com
// baidu--Address:112.80.248.73
// baidu--name:www.baidu.com
}
}
</strong>
需求:通过UDP传输方式 将一段文字数据发送出去。
定义一个UDP发送端
思路:
1.建立udpsocket服务
2.提供数据,并将数据封装到数据包中
3.通过socket服务的发送功能,将数据包发出去
4.关闭资源。
发送端:
例子2:
<strong>public class UDPSentDemo {
public static void main(String[] args) throws Exception {
// 1.创建一个UDP服务, 通过DatagramSocket对象,并指定发送使用的端口号为8888(如果不设置,系统随机安排端口)
DatagramSocket ds = new DatagramSocket(8888);
// 2.确定数据,并封装成数据包
byte[] buf = "udp welcom to".getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("171.39.84.202"), 10000);
// 3. 发送
ds.send(dp);
// 4.关闭资源
ds.close();
}
}</strong>
接收端:
例子3:
<strong>public class UDPReceiveDemo {
public static void main(String[] args) throws Exception {
// 1.创建一个UDP服务, 通过DatagramSocket对象,并设置监听的端口号10000
DatagramSocket ds = new DatagramSocket(10000);
// 2.定义数据包,接受数据包,并封装成数据包
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
// 3. 接受数据,将收到的数据存入数据包中
ds.receive(dp); //阻塞式方法,没收到数据时,将处于阻塞状态
// 将字节数组数据转变成字符串
String data = new String(dp.getData(), 0, dp.getLength());
// 发送者的IP
String address = dp.getAddress().getHostAddress();
// 发送者发送使用的端口号
int port = dp.getPort();
System.out.println("send IP:" + address);
System.out.println("Data:" + data);
System.out.println("send port:" + port);
// 4.关闭资源
ds.close();
/*
* 运行结果:send IP:171.39.84.202
* Data:udp welcom to send
* port:8888
*/
}
}</strong>
需求:键盘录入数据发送到别的客户端,输入886停止发送
例子4:
发送端
<strong>public class UDPSent {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(8888);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = in.readLine()) != null) {
if (line.equals("886"))
break;
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("171.39.84.202"), 10001);
ds.send(dp);
}
ds.close();
}
}</strong>
需求: 接受发送方一直发送的数据 ,不用关闭资源
例子5:
发送端
public class UDPReceive {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(10001);
while (true) {
byte[] buf = new byte[1024 * 64]; // 一个UDP数据包最大为64kb
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String data = new String(dp.getData(), 0, dp.getLength());
String address = dp.getAddress().getHostAddress();
System.out.println(address + "-------" + data);
}
}
}
需求:制作一个聊天工具
例子6:
public class ChatDemo {
public static void main(String[] args) throws Exception {
DatagramSocket send = new DatagramSocket(8880);
DatagramSocket receive = new DatagramSocket(10003);
new Thread(new Sent(send)).start();
new Thread(new Receive(receive)).start();
}
}
// 发送的线程
class Sent implements Runnable {
private DatagramSocket ds;
public Sent(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
while ((line = in.readLine()) != null) {
if ("886".equals(line))
break;
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("171.39.84.255"), 10002);
ds.send(dp);
}
} catch (Exception e) {
new RuntimeException("发送端失败");
}
}
}
// 接受线程
class Receive implements Runnable {
private DatagramSocket ds;
public Receive(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
while (true) {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String data = new String(dp.getData(), 0, dp.getLength());
String address = dp.getAddress().getHostAddress();
System.out.println(address + "---->" + data);
}
} catch (Exception e) {
new RuntimeException("接收端失败");
}
}
}
客户端:
例子7:
public class TcpClient {
public static void main(String[] args) throws Exception {
//创建客户端的socket服务,指定目的主机和端口
Socket s = new Socket("171.39.85.95", 10005);
//为了发送数据,应该获取socket流中输出流
OutputStream in = s.getOutputStream();
in.write("i am tcp".getBytes());
s.close();
}
}
需求:定义端点接受数据并打印在控制台上
服务端:
例子8:
public class TcpServer {
public static void main(String[] args) throws Exception {
//建立服务端socket服务,并监听一个端口
ServerSocket ss = new ServerSocket(10005);
//通过accept方法获取连接过来的客户端对象
Socket s = ss.accept();
//获取客户端发过来的数据,那么要使用客户端对象的读取流来读取数据
InputStream in = s.getInputStream();
byte[] by = new byte[1024];
int len = in.read(by);
String data = new String(by,0,len);
InetAddress ia = s.getInetAddress();
String ip = ia.getHostAddress();
System.out.println(ip+"--->"+data);
s.close();
}
}
class TransClient {
public static void main(String[] args) throws Exception {
// 创建客户端的socket服务,指定目的主机和端口
Socket s = new Socket("171.39.85.95",10009);
//定义读取键盘数据的流对象
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//定义一个socket读取流,读取服务端返回的大写信息
BufferedReader bufin = new BufferedReader(new InputStreamReader(
s.getInputStream()));
//定义目的,将数据写入到socket输出流,发给客户端
BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
String line = null;
while ((line = in.readLine()) != null) {
if("over".equals(line))
break;
bufout.write(line);
//一定要添加换行,不然服务端接受不到换行符,将会一直处于阻塞状态
bufout.newLine();
bufout.flush();
String serverData = bufin.readLine();
System.out.println(serverData);
}
s.close();
}
}
class TransServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10009);
Socket s = ss.accept();
//获取发送端的IP地址
String clientIP = ss.getInetAddress().getHostAddress();
System.out.println(clientIP+"......access");
//读取socket读取流中的数据
BufferedReader bufin = new BufferedReader(new InputStreamReader(
s.getInputStream()));
//目的,socket输出流,将大写数据写入到socket输出流中,并发送给客户端
BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
String line = null;
while ((line = bufin.readLine()) != null) {
System.out.println(line);
bufout.write("server:"+line.toUpperCase());
bufout.newLine();
bufout.flush();
}
s.close();
ss.close();
}
}
class TcpClientDemo {
public static void main(String[] args) throws Exception {
// 创建客户端的socket服务,指定目的主机和端口
Socket s = new Socket("171.39.85.95", 10005);
// 为了发送数据,应该获取socket流中输出流
OutputStream out = s.getOutputStream();
out.write("i am tcp".getBytes());
// 接受服务端发回的数据
InputStream in = s.getInputStream();
byte[] bt = new byte[1024];
int len = in.read(bt);
System.out.println(new String(bt, 0, len));
s.close();
}
}
class TcpServerDemo {
public static void main(String[] args)throws Exception {
// 建立服务端socket服务,并监听一个端口
ServerSocket ss = new ServerSocket(10005);
// 通过accept方法获取连接过来的客户端对象
Socket s = ss.accept();
// 获取客户端发过来的数据,那么要使用客户端对象的读取流来读取数据
InputStream in = s.getInputStream();
byte[] by = new byte[1024];
int len = in.read(by);
String data = new String(by, 0, len);
//返回给客户端信息
OutputStream out = s.getOutputStream();
Thread.sleep(5000);
out.write("服务端已经收到!!!!!".getBytes());
InetAddress ia = s.getInetAddress();
String ip = ia.getHostAddress();
System.out.println(ip + "--->" + data);
s.close();
ss.close();
}
}
需求:将一个文本文件上传到服务端
例子11:
<strong>//客户端
class TextClient {
public static void main(String[] args) throws Exception {
// 创建客户端的socket服务,指定目的主机和端口
Socket s = new Socket("127.0.0.1", 10009);
// 需要上传的文件
BufferedReader in = new BufferedReader(new FileReader(
"FileReaderDemo_copyByBuf.txt"));
// 网络上传传输流
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
String line = null;
while ((line = in.readLine()) != null) {
out.println(line);
}
s.shutdownOutput(); // 上传的结束标记,关闭客户端的输出流,相当于给流中加入一个结束标记
// 服务器返回数据
BufferedReader server = new BufferedReader(new InputStreamReader(
s.getInputStream()));
String str = server.readLine();
System.out.println("server:" + str);
in.close();
s.close();
}
}
// 服务端
class TexServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10009);
Socket s = ss.accept();
// 获取发送端的IP地址
String clientIP = ss.getInetAddress().getHostAddress();
System.out.println(clientIP + "......access");
// 读取socket读取流中的数据
BufferedReader bufin = new BufferedReader(new InputStreamReader(
s.getInputStream()));
PrintWriter pw = new PrintWriter(new FileWriter("server.java"), true);
String line = null;
while ((line = bufin.readLine()) != null) {
pw.println(line);
}
// 目的,socket输出流,将大写数据写入到socket输出流中,并发送给客户端
PrintWriter client = new PrintWriter(s.getOutputStream(), true);
client.println("上传成功");
s.close();
ss.close();
}
}</strong>
服务端
例子12:
class PicClient {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("请选择一个jpg格式的图片");
return;
}
File file = new File(args[0]);
if (!(file.exists() && file.isFile())) {
System.out.println("该文件有问题,要么不存在,要么不是文件");
return;
}
if (!file.getName().endsWith(".jpg")) {
System.out.println("图片格式错误,请重新选择");
return;
}
if (file.length() > 1024 * 1024 * 8) {
System.out.println("文件超过8M,不能上传");
return;
}
Socket s = new Socket("171.39.87.39", 10007);
FileInputStream fis = new FileInputStream(file);
OutputStream out = s.getOutputStream();
byte[] by = new byte[1024];
int len = 0;
while ((len = fis.read(by)) != -1) {
out.write(by, 0, len);
}
// 通知服务端数据已写完
s.shutdownOutput();
InputStream in = s.getInputStream();
byte[] bufIn = new byte[1024];
int num = in.read(bufIn);
System.out.println(new String(bufIn, 0, num));
fis.close();
s.close();
}
}
class PicThread implements Runnable {
private Socket s;
PicThread(Socket s) {
this.s = s;
}
@Override
public void run() {
// 获取客户端IP
String ip = s.getInetAddress().getHostAddress();
int count = 1;
try {
System.out.println(ip+".....conetion");
File file = new File(ip + "(" + count + ").jpg");
while(file.exists()) {
file = new File(ip + "(" + (count++) + ").jpg");
}
InputStream in = s.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
OutputStream out = s.getOutputStream();
out.write("上传成功".getBytes());
fos.close();
s.close();
} catch (Exception e) {
throw new RuntimeException("线程上传失败!");
}
}
}
/*
服务端
*/
class PicServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10007);
while (true) {
Socket s = ss.accept();
new Thread(new PicThread(s)).start();
}
}
}
例子13:
class LoginClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("171.39.84.2", 10008);
BufferedReader bufr = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
for (int i = 0; i < 3; i++) {
String line = bufr.readLine();
if (line == null)
break;
out.println(line);
String info = in.readLine();
System.out.println("info:" + info);
if (info.contains("欢迎"))
break;
}
bufr.close();
s.close();
}
}
class UserThread implements Runnable {
private Socket s;
UserThread(Socket s) {
this.s = s;
}
@Override
public void run() {
String IP = s.getInetAddress().getHostAddress();
System.out.println(IP+"....connected");
try {
for (int i = 0; i < 3; i++) {
BufferedReader bufr = new BufferedReader(new FileReader(
"user.txt"));
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
String username = in.readLine();
if(username == null)
break;
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
String line = null;
boolean flag = false;
while((line = bufr.readLine()) != null){
if(line.equals(username)){
flag = true;
break;
}
}
if(flag){
out.println(username+"欢迎您");
System.out.println(IP+"::"+username+"::"+"用户已登入");
}else{
out.println("用户不存在");
}
}
s.close();
} catch (Exception e) {
throw new RuntimeException("检验失败");
}
}
}
class LoginServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10008);
while (true) {
Socket s = ss.accept();
new Thread(new UserThread(s)).start();
}
}
}
需求:自定义一个客户端,向Tomcat服务端发送请求
例子14:
public class MyIE {
public static void main(String[] args) throws Exception {
Socket s = new Socket("171.39.84.2",8080);
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
//模仿浏览器方式发送数据给TOmcat服务端
out.println("GET /myweb/demo.html HTTP/1.1");
out.println("Accept:*/*");
out.println("Host: 171.39.84.2:11000");
out.println("Cache-Control: max-age=0");
out.println("Accept-Language: zh-CN,zh;q=0.8");
out.println("Accept-Encoding: gzip,deflate,sdch");
out.println("Connection: keep-alive");
out.println();
out.println();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while((line=in.readLine()) != null){
System.out.println(line);
}
s.close();
}
}
/*
*
Tomcat服务端想客户端发送回来的数据
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"156-1431832945631"
Last-Modified: Sun, 17 May 2015 03:22:25 GMT
Content-Type: text/html
Content-Length: 156
Date: Sun, 17 May 2015 03:22:33 GMT
<html>
<head>
<title>welcome to beijing </title>
</head>
<body>
<h>welcome to myweb</h>
<div >
jkfafelfsaljfdslfflemsfmek
</div>
</body>
*/
String getFile()
例子15:
public class URlDemo {
public static void main(String[] args) throws Exception {
URL url = new URL("http://171.39.86.245:8080/myweb/demo.html?username=lisi");
System.out.println("getProtocol() :" + url.getProtocol());
System.out.println("getFile() :" + url.getFile());
System.out.println("getHost() :" + url.getHost());
System.out.println("getPath() :" + url.getPath());
System.out.println("getQuery() :" + url.getQuery());
}
}
例子16:
public class ServerDemo {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10011);
Socket s = ss.accept();
System.out.println(s.getInetAddress().getHostAddress()+".......connected");
InputStream in = s.getInputStream();
byte[] bt = new byte[1024];
int len = in.read(bt);
System.out.println(new String(bt,0,len));
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
// out.println("<font color='red' size='3'>欢迎访问服务端</font>");
out.println("welcom to beijing ");
s.close();
ss.close();
}
}
/*
*
浏览器客户端想服务端发来的数据;
GET / HTTP/1.1
Host: 171.39.84.2:10011
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8
*/
例子17:
public class MyIE {
public static void main(String[] args) throws Exception {
Socket s = new Socket("171.39.84.2",8080);
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
//模仿浏览器方式发送数据给TOmcat服务端
out.println("GET /myweb/demo.html HTTP/1.1");
out.println("Accept:*/*");
out.println("Host: 171.39.84.2:11000");
out.println("Cache-Control: max-age=0");
out.println("Accept-Language: zh-CN,zh;q=0.8");
out.println("Accept-Encoding: gzip,deflate,sdch");
out.println("Connection: keep-alive");
out.println();
out.println();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while((line=in.readLine()) != null){
System.out.println(line);
}
s.close();
}
}
/*
*
Tomcat服务端想客户端发送回来的数据
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"156-1431832945631"
Last-Modified: Sun, 17 May 2015 03:22:25 GMT
Content-Type: text/html
Content-Length: 156
Date: Sun, 17 May 2015 03:22:33 GMT
<html>
<head>
<title>welcome to beijing </title>
</head>
<body>
<h>welcome to myweb</h>
<div >
jkfafelfsaljfdslfflemsfmek
</div>
</body>
*/