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>
*/