java 中的InetAddress类简单介绍

InetAddress类是Java包装用来表示IP地址的高级表示。几乎所有的Java网络相关的类都和它有关系,例如:serversocket,socket,URL,DataGramSocket,DataGRamPacket等。
下面就InetAddress所提供的一些类做一个简单的介绍。
1.InetAddress.getByName()
通过主机名获取对应的ip地址:(当然也支持通过IP地址来查找主机名)
该方法会建立与本地DNS的一个连接,来获取名称和地址之间的映射关系。(如果本地DNS缓存了地址,就不再获取连接。)
2**.InetAddress.getLocalHost()**
得到真正的主机名和IP地址。如果获取失败,则会返回一个会送地址,即主机名为“localhost”,以及一个点四分段的ip:‘127.0.0.1’ 。

3**缓存**
由于DNS查找的开销很大,并且如果一个地址不可达,可能会需要几秒钟的时间来确认。InetAddress提供了缓存机制,一旦得到一个给定主机的地址,就会缓存起来,即使重新定义一个InetAddress类,也不会重新再获取一次,而是直接从缓存中获取。但是需要注意一种情况。就是DNS在传输过程中可能的超时。当第一次请求是发生超时失败,而第二次的时候请求已经到达,并缓存了起来。所有Java在缓存不可达的地址时,只缓存了10s。
4.安全性问题
从主机名创建一个InetAddress对象,被认为是一种不安全的操作。因为这需要一个DNS查找,在默认的安全管理控制器下的不可行applet只允许获取它本机的主机地址以及ip。不允许不可行代码由任何其他主机名创建InetAddress对象。不可信的代码不允许对第三方主机完成任意查找。
5.获取方法
public String getHostName()

publlic String getCanonicalHostName()

public byte[] getAddress()

public String getHostAddress()
没有对应的setHostName()以及getHostName()。代表着无法通过反射来改变其内部的。因此是线程安全的。
6.地址类型
ip地址分为不同的类型,例如:‘’127.0.0.1‘’属于本地回送地址。Java提供了10中方法来判断一个ip地址属于那种不同的分段。
public boolean isAnyLocalAddress()

  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来回答你的问题。 首先,我们需要了解一下 ServerSocket、Socket 和 InetAddress 这三个的作用: - ServerSocket:用于监听客户端的连接请求,并创建对应的 Socket 对象进行通信。 - Socket:用于与服务器建立连接并进行通信。 - InetAddress:用于表示 IP 地址。 接下来,我们可以开始编写聊天程序了。下面是一个简单Java 聊天程序的代码: 1. 服务器端代码: ```java import java.io.*; import java.net.*; import javax.swing.*; public class Server extends JFrame { private JTextField userText; private JTextArea chatWindow; private ObjectOutputStream output; private ObjectInputStream input; private ServerSocket server; private Socket connection; // 构造方法 public Server() { super("Server"); userText = new JTextField(); userText.setEditable(false); userText.addActionListener(event -> sendMessage(event.getActionCommand())); add(userText, BorderLayout.NORTH); chatWindow = new JTextArea(); add(new JScrollPane(chatWindow)); setSize(300, 150); setVisible(true); } // 启动服务器 public void startRunning() { try { server = new ServerSocket(7777, 100); while (true) { try { waitForConnection(); setupStreams(); whileChatting(); } catch (EOFException eofException) { showMessage("\nServer ended the connection!"); } finally { closeCrap(); } } } catch (IOException ioException) { ioException.printStackTrace(); } } // 等待连接 private void waitForConnection() throws IOException { showMessage("Waiting for someone to connect...\n"); connection = server.accept(); showMessage("Now connected to " + connection.getInetAddress().getHostName()); } // 设置流 private void setupStreams() throws IOException { output = new ObjectOutputStream(connection.getOutputStream()); output.flush(); input = new ObjectInputStream(connection.getInputStream()); showMessage("\nStreams are now setup!\n"); } // 聊天 private void whileChatting() throws IOException { String message = "You are now connected!"; sendMessage(message); ableToType(true); do { try { message = (String) input.readObject(); showMessage("\n" + message); } catch (ClassNotFoundException classNotFoundException) { showMessage("\nUnknown object type received!"); } } while (!message.equals("CLIENT - END")); } // 关闭连接 private void closeCrap() { showMessage("\nClosing connections...\n"); ableToType(false); try { output.close(); input.close(); connection.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } // 发送消息 private void sendMessage(String message) { try { output.writeObject("SERVER - " + message); output.flush(); showMessage("\nSERVER - " + message); } catch (IOException ioException) { chatWindow.append("\nERROR: Cannot send message!"); } } // 更新聊天窗口 private void showMessage(String message) { SwingUtilities.invokeLater(() -> chatWindow.append(message)); } // 是否可以输入 private void ableToType(boolean tof) { SwingUtilities.invokeLater(() -> userText.setEditable(tof)); } } ``` 2. 客户端代码: ```java import java.io.*; import java.net.*; import javax.swing.*; public class Client extends JFrame { private JTextField userText; private JTextArea chatWindow; private ObjectOutputStream output; private ObjectInputStream input; private String message = ""; private String serverIP; private Socket connection; // 构造方法 public Client(String host) { super("Client"); serverIP = host; userText = new JTextField(); userText.setEditable(false); userText.addActionListener(event -> sendMessage(event.getActionCommand())); add(userText, BorderLayout.NORTH); chatWindow = new JTextArea(); add(new JScrollPane(chatWindow)); setSize(300, 150); setVisible(true); } // 连接到服务器 public void startRunning() { try { connectToServer(); setupStreams(); whileChatting(); } catch (EOFException eofException) { showMessage("\nClient terminated the connection!"); } catch (IOException ioException) { ioException.printStackTrace(); } finally { closeCrap(); } } // 连接到服务器 private void connectToServer() throws IOException { showMessage("Attempting connection...\n"); connection = new Socket(InetAddress.getByName(serverIP), 7777); showMessage("Connected to: " + connection.getInetAddress().getHostName()); } // 设置流 private void setupStreams() throws IOException { output = new ObjectOutputStream(connection.getOutputStream()); output.flush(); input = new ObjectInputStream(connection.getInputStream()); showMessage("\nStreams are now setup!\n"); } // 聊天 private void whileChatting() throws IOException { ableToType(true); do { try { message = (String) input.readObject(); showMessage("\n" + message); } catch (ClassNotFoundException classNotFoundException) { showMessage("\nUnknown object type received!"); } } while (!message.equals("SERVER - END")); } // 关闭连接 private void closeCrap() { showMessage("\nClosing connections...\n"); ableToType(false); try { output.close(); input.close(); connection.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } // 发送消息 private void sendMessage(String message) { try { output.writeObject("CLIENT - " + message); output.flush(); showMessage("\nCLIENT - " + message); } catch (IOException ioException) { chatWindow.append("\nERROR: Cannot send message!"); } } // 更新聊天窗口 private void showMessage(String message) { SwingUtilities.invokeLater(() -> chatWindow.append(message)); } // 是否可以输入 private void ableToType(boolean tof) { SwingUtilities.invokeLater(() -> userText.setEditable(tof)); } } ``` 以上就是一个使用 ServerSocket 和 Socket 以及 InetAddress 编写的简单聊天程序的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值