"Network Programming" inetaddress, TCP, UDP

Source: Internet
Author: User
Tags get ip

InetAddress

Importjava.net.InetAddress;Importjava.net.UnknownHostException;/** Indicates the IP address in the Internet * java.net.InetAddress * static method * Statics inetaddress getlocalhost () localhost Local host * Returns the local host, return value inetaddress Object * static inetaddress Getbyname (String hostName) pass host name, get IP Address Object * * Non-static method * String Gethou Staddress () Gets the host IP address * String gethoustname () gets the host name **/ Public classInetaddressdemo { Public Static voidMain (string[] args)throwsunknownhostexception {function_1 (); }    /** Static inetaddress Getbyname (String hostName) to pass host name, get IP Address object*/     Public Static voidFunction_1 ()throwsunknownhostexception {inetaddress inet= Inetaddress.getbyname ("www.baidu.com");    System.out.println (inet); }        /** static inetaddress getlocalhost () localhost Local host*/     Public Static voidfunction ()throwsunknownhostexception{inetaddress inet=Inetaddress.getlocalhost (); //the output is the host name, and the IP addressSystem.out.println (inet.tostring ()); String IP=inet.gethostaddress (); String name=Inet.gethostname (); SYSTEM.OUT.PRINTLN (IP+"   "+name); /*String host = inet.tostring ();        string[] str = host.split ("/");        for (String s:str) {System.out.println (s); }*/    }}

UDP Send Side

Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;/** Implementation of the UDP protocol send side: * The class that implements the encapsulated data Java.net.DatagramPacket your data wrapping * Class Java.net.DatagramSocket data transmission send the packet out * * Implementation steps: * 1. Create the Datagrampacket object, encapsulate the data, receive the address and port * 2. Create Datagramsocket * 3. Call the Datagramsocket class method send, which sends the packet * 4.       Close Resource * * Datagrampacket construction Method: * Datagrampacket (byte[] buf, int length, inetaddress address, int port) * * Datagramsocket Construction Method: * Datagramsocket () Null parameter * method: Send (Datagrampacket d) **/ Public classUdpsend { Public Static voidMain (string[] args)throwsioexception{//Create a Packet object, encapsulate the data to be sent, receive-side IP, Port        byte[] date = "Hello UDP". GetBytes (); //Create a InetAddress object that encapsulates its own IP addressInetAddress inet = Inetaddress.getbyname ("127.0.0.1"); Datagrampacket DP=NewDatagrampacket (date, date.length, inet,6000); //Create a Datagramsocket object, send and receive objects for a packetDatagramsocket ds =NewDatagramsocket (); //method of calling DS object send, send packetDs.send (DP); //Close ResourceDs.close (); }}

UDP Receive End

Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;/** Implement UDP Receiver * Implement package packet Java.net.DatagramPacket data packet * Implement output transmit Java.net.DatagramSocket receive packet * * Implementation steps: * 1. Create the Datagramsocket object, bind the port number * to be the same as the sender port number * 2. Creates an array of bytes, receiving the data sent by * 3. Create a Packet object Datagrampacket * 4. Call the Datagramsocket object method * Receive (Datagrampacket DP) and put the data in the packet * 5.          Unpacking * Sent IP address * Packet Object Datagrampacket method GetAddress () Gets the IP address object of the sending end * The return value is inetaddress object * Number of bytes received * Packet Object Datagrampacket method getlength () * Sender's port number * Packet Object Datagrampacket method Getport () Send Port * 6. Close Resource*/ Public classudpreceive { Public Static voidMain (string[] args)throwsIOException {//Creating a Packet transport object Datagramsocket binding port numberDatagramsocket ds =NewDatagramsocket (6000); //creating a byte array        byte[] data =New byte[1024]; //creating a Packet object, passing a byte arrayDatagrampacket DP =Newdatagrampacket (data, data.length); //Call the DS object method receive to pass the packetDs.receive (DP); //Gets the IP address object for the Send sideString ip=dp.getaddress (). gethostaddress (); //get the port number sent        intPort =Dp.getport (); //Gets the number of bytes received        intLength =dp.getlength (); System.out.println (NewString (data,0,length) + "..." +ip+ ":" +port);    Ds.close (); }}

Expansion: Using UDP to implement keyboard input chat

UDP Send Side

Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;ImportJava.util.Scanner;/** Implementation of UDP send, keyboard input form * Input completed, sent to the receiving end*/ Public classUdpsend { Public Static voidMain (string[] args)throwsioexception{Scanner SC=NewScanner (system.in); Datagramsocket DS=NewDatagramsocket (); InetAddress inet= Inetaddress.getbyname ("127.0.0.1");  while(true) {String message=Sc.nextline (); /*if ("886". Equals (Message)) {break; }*/        byte[] Date =message.getbytes (); Datagrampacket DP=NewDatagrampacket (date, date.length, inet,6000);        Ds.send (DP); }    //ds.close ();    }}

UDP Receive End

Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;/** Implementation of UDP receiver * Never stop receiving end*/ Public classudpreceive { Public Static voidMain (string[] args)throwsIOException {//Creating a Packet transport object Datagramsocket binding port numberDatagramsocket ds =NewDatagramsocket (6000); //creating a byte array        byte[] data =New byte[1024]; //creating a Packet object, passing a byte array         while(true) {Datagrampacket DP=Newdatagrampacket (data, data.length); //Call the DS object method receive to pass the packetDs.receive (DP); //Gets the IP address object for the Send sideString ip=dp.getaddress (). gethostaddress (); //get the port number sent        intPort =Dp.getport (); //Gets the number of bytes received        intLength =dp.getlength (); System.out.println (NewString (data,0,length) + "..." +ip+ ":" +port); }        //ds.close ();    }}

TCP Client (sender side)

Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.Socket;/** Implement TCP client , connect to server * and server implement data exchange * Implement TCP client program class Java.net.Socket * * Constructor Method: * Socket (String host, int port) Recursive server IP and port number * Note: The construction method will be connected to the server as long as it is running, the connection fails, the exception is thrown * * OutputStream Getoutputstream () returns the output stream of socket * Function: Data output , Output to Server * * InputStream getinputstream () return socket input stream * Function: Read data from server * * Client server data exchange, must use socket object in socket Get the IO stream, own new stream, no*/ Public classTCPClient { Public Static voidMain (string[] args)throwsIOException {//create a socket object to connect to the serverSocket socket =NewSocket ("127.0.0.1", 8888); //through the client socket object socket method, gets the byte output stream, writes the data to the serverOutputStream out =Socket.getoutputstream (); Out.write ("Server OK". GetBytes ()); //reads the data sent back by the server, using the byte input stream in the socket socket objectInputStream in =Socket.getinputstream (); byte[] data =New byte[1024]; intLen =in.read (data); System.out.println (NewString (data,0, Len));    Socket.close (); }}

TCP Server (Receive side)

 PackageCn.itcast.demo3;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket;/** Implementation of the TCP server program * represents the class of the server program Java.net.ServerSocket * Construction Method: * ServerSocket (int port) Pass Port number * Important thing: You have to get the client's sleeve Socket Object Socket * Socket accept ()*/ Public classTCPServer { Public Static voidMain (string[] args)throwsioexception{ServerSocket Server=NewServerSocket (8888); //call the method in the server socket object accept () to get the client socket objectSocket socket =server.accept (); //through the client socket object, the socket gets the byte input stream and reads the data sent by the client .InputStream in =Socket.getinputstream (); byte[] data =New byte[1024]; intLen =in.read (data); System.out.println (NewString (data,0, Len)); //The server returns the data to the client, the byte output stream, and the byte output stream through the client socket objectOutputStream out =Socket.getoutputstream (); Out.write ("Roger that, thank you.". GetBytes ());        Socket.close ();    Server.close (); }}

"Network Programming" inetaddress, TCP, UDP

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.