Java Network Programming (2) InetAddress Class and UDP protocol

Source: Internet
Author: User
Tags fully qualified domain name

InetAddress class

The JDK provides a java.neT Package for developing network applications, and the classes and interfaces under the package are almost all for network programming services.

InetAddress: An object used to describe an IP address

The InetAddress class does not provide a constructor method,

Instead, a static method is provided to get the InetAddress instance

    1. Getbyname (String host): gets the corresponding InetAddress object based on the host.
    2. getbyaddress (byte[] addr): gets the corresponding InetAddress object based on the original IP address.
    3. Getallbyname (String host): Returns an array

Three ways to get the IP address and host name for the InetAddress instance

    1. String getcanonicalhostname (): fully qualified domain name for this IP address
    2. String gethostname (): host name for instance
    3. String gethostaddress (): The IP address that the instance corresponds to

Package Net.csdn.web;import Java.io.ioexception;import Java.net.inetaddress;public class Demo1 {/** * @param args * @thro WS IOException */public static void Main (string[] args) throws IOException {        //based on host name To obtain the corresponding inetaddress instance         inetaddress ia = inetaddress.getbyname ("192.168.49.50");                 //determine if it's up to         system.out.println ("oneedu is reachable" +ia.isreachable);        // Gets the IP string for the inetaddress instance         system.out.println (ia.gethostaddress ());        //Gets the host name of the IP string for the inetaddress instance         system.out.println ( Ia.gethostname ());        //Gets the fully qualified domain name of the IP address of the InetAddress instance          system.out.println (Ia.getcanonicalhostname ());       &Nbsp;        //to get the corresponding InetAddress instance array based on the hostname          inetaddress[] IP = inetaddress.getallbyname ("www.baidu.com");        //traversing array          for (inetaddress i:ip) {             System.out.println (I.gethostaddress () +i.gethostname ());        }     }}


The output results are as follows:


UDP What is a UDP protocol?

The UDP (user Datagram Protocol) protocol is a user datagram that is used in the network as the TCP protocol for processing packets. In the OSI model, the fourth layer, the transport layer, is in the upper layer of the IP protocol.

UDP is a non-connected protocol , each datagram is a separate information, including the full source or destination address, it on the network with any possible path to the destination, so can reach the destination, the time to reach the destination and the correctness of the content is not guaranteed.

File <64k


Why use UDP?

In an environment where the quality of the network is unsatisfactory, the packet loss of UDP protocol is more serious. However, because of the characteristics of UDP: it does not belong to the connection protocol, thus has the advantage of small resource consumption, processing speed , so usually audio, video and ordinary data in the transmission of UDP more use, because they even occasionally lost one or two packets, Will not have much effect on receiving results. For example, the chat with ICQ and OICQ is the use of the UDP protocol.


manipulating UDP in Java

Using the Datagramsocket and Datagrampacket classes located under the Java.net package in the JDK, you can easily control user data messages.


Datagramsocket class: Creating a socket instance that receives and sends UDP

datagramsocket (): creates an instance. Typically used for client-side programming, it does not have a specific listening port, just using a temporary one.

datagramsocket (int port): creates an instance and secures a message that listens on port ports.

datagramsocket (int port, INETADDRESSLOCALADDR): This is a very useful builder, when a machine has more than one IP address, the instance created by it only receives messages from LOCALADDR.

Note: When creating an instance of the Datagramsocket class, if the port is already in use, a SocketException exception is thrown and the program terminates illegally, and the exception should be aware of the catch.

Receive (Datagrampacket D): receives data messages into ' d. The Receive method produces a "blocking".

"Blocking" is a professional noun that produces an internal loop that causes the program to pause in this place until a condition is triggered.

Send (Datagrampacket d): send paper D to destination.

setsotimeout (int timeout): sets the time-out period in milliseconds.

Close (): datagramsocket off. When an application exits, it usually releases the resource voluntarily, shutting down the socket, but may cause the resource not to be reclaimed due to an unexpected exit. Therefore, you should actively use this method to close the socket when the program completes, or to close the socket after catching the exception thrown.


Datagrampacket: Used to process the message, the byte array, the destination address, the destination port, and other data packaging into a message or the message is disassembled into a byte array.

Datagrampacket (byte[] buf, int length,inetaddress addr, int port): extracts Long data from the BUF array to create a packet object, with the destination addr address, Port ports.

Datagrampacket (byte[] buf, int offset, intlength, inetaddress address, int port): from the BUF array, remove the start of offset, Length data creates a packet object with the destination addr address, port.

Datagrampacket (byte[] buf, int offset, intlength): Load data in the packet from offset, long length, into the BUF array.

Datagrampacket (byte[] buf, int length): The length of data in the packet is loaded into the BUF array.

getData (): It obtains a byte array encoding of the message from the instance.



Example 1: Write a program that demonstrates the use of UDP protocol datagrams for sending and receiving.

Send Side

Package Net.csdn.web;import Java.io.ioexception;import Java.net.datagrampacket;import java.net.DatagramSocket; Import Java.net.inetaddress;public class Demosend {public static void main (string[] args) throws IOException {//1. Build Udpso Cket the service endpoint. The endpoint is established and the system randomly assigns a port. If you do not want to configure randomly, you can specify it manually. Datagramsocket ds = new Datagramsocket ();//2. To encapsulate the data in a packet package, you must specify the destination address and port. byte[] buf = "Wo shi Shu ju". getBytes (); InetAddress is = Inetaddress.getbyname ("192.168.49.50");D atagrampacket dp = new Da Tagrampacket (buf, buf.length,is,9009);//3. The packet is emitted by the Send method of the socket service. Ds.send (DP);//4. Close the socket service. The main is to close resources. Ds.close ();}}

Receiving end

Package Net.csdn.web;import Java.io.ioexception;import Java.net.datagrampacket;import java.net.DatagramSocket; public class Demoreceive {public static void main (string[] args) throws IOException {//1. Create a UDP socket service. To listen on a port. Datagramsocket ds = new Datagramsocket (9009);//2. Defines a buffer that encapsulates the buffer into a packet package. byte[] buf = new byte[1024];D atagrampacket dp = new Datagrampacket (buf, buf.length);//3. Data is stored in the packet via the socket's receive method. Ds.receive (DP);//4. Gets the specified information in the package by means of the packet DP Method GetData (), getaddress (), Getport (), and so on. String IP = dp.getaddress (). gethostaddress (); String data = new String (Dp.getdata (), 0,dp.getlength ()); int port = Dp.getport (); System.out.println (ip+ ":" +data+ ":" +port);//5. Close the socket. Ds.close ();}}


Open with the cmd command window:


Example 2: Writing programs to demonstrate the use of UDP protocol datagram send and receive, can be input from the keyboard

Send Side

Package Net.csdn.web;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStreamReader; Import Java.net.datagrampacket;import Java.net.datagramsocket;import Java.net.inetaddress;public class DemoSend2 {/* * * @param args */public static void main (string[] args) throws IOException {//TODO auto-generated method Stubdatagramsoc Ket ds = new Datagramsocket (); BufferedReader br = new BufferedReader (new InputStreamReader (system.in)); String line = null;while (line = Br.readline ())! = null) {if (Line.equals (888)) {break;} byte[] buf = line.getbytes ();D atagrampacket dp = new Datagrampacket (buf, Buf.length,inetaddress.getbyname (" 192.168.49.255 "), 9009);d S.send (DP);} Ds.close ();}}


Receiving end

Package Net.csdn.web;import Java.io.ioexception;import Java.net.datagrampacket;import java.net.DatagramSocket; public class DemoReceive2 {public static void main (string[] args) throws IOException {//TODO auto-generated method Stubda Tagramsocket ds = new Datagramsocket (9009), while (true) {byte[] buf = new byte[1024];D atagrampacket dp = new Datagrampacket ( BUF, Buf.length);d s.receive (DP); String IP = dp.getaddress (). gethostaddress (); String data = new String (Dp.getdata (), 0,dp.getlength ()); System.out.println (ip+ ":" +data);}}}



dialog box to send and receive in the same region

Package Src.com.hbsi.net;import Java.net.*;import java.io.*;p ublic class Chatdemo {/** * @param args */public static void Main (string[] args) {try {datagramsocket send=new datagramsocket ();D atagramsocket rece=new datagramsocket (9008); new Thread (new Chatsend (send)). Start (); New Thread (New Chatrece (Rece)). Start (); catch (SocketException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}        Class Chatsend implements runnable{Datagramsocket ds;    Public Chatsend (Datagramsocket ds) {this.ds=ds; } @Overridepublic void Run () {Try{bufferedreader br=new BufferedReader (New InputStreamReader (system.in)); String Line=null;while ((Line=br.readline ())!=null) {if (Line.equals ("Over")) break;byte[] Buf=line.getbytes ();D Atagrampacket dp=new Datagrampacket (Buf,buf.length,inetaddress.getbyname ("192.168.49.255"), 9008);d S.send (DP);} Ds.close ();} catch (Exception e) {e.printstacktrace ();}}}     Class Chatrece implements runnable{Datagramsocket ds; Public chatrece (Datagramsocket DS) {this.Ds=ds; } @Overridepublic void Run () {while (true) {try{byte[] buf=new byte[1024];D atagrampacket dp=new datagrampacket (buf, Buf.length);d s.receive (DP); String ip=dp.getaddress (). gethostaddress (); String Data=new string (Dp.getdata (), 0,dp.getlength ()); System.out.println (ip+ ":" +data);} catch (Exception e) {e.printstacktrace ();}}}}



Reprint please indicate address http://blog.csdn.net/zhaoyazhi2129/article/details/40422301

Java Network Programming (2) InetAddress Class and UDP protocol

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.