Java Network Programming from entry to mastery (28): Methods for obtaining ServerSocket information and FTP principles

Source: Internet
Author: User

AndServerSocketThere are two types of Object-related information: binding port and bindingIPAddress. You can useGetLocalPortMethod. BindIPYou can useGetInetAddressMethod.

I,GetLocalPortMethod

GetLocalPortThe return values of a method can be divided into the following three situations:

1.ServerSocketThe object is not bound to a port,GetLocalPortThe Return Value of the method is-1.

2.ServerSocketThe object is bound to a fixed port,GetLocalPortMethod to return this fixed port.

3. ServerSocketThe binding port of the object is0,GetLocalPortMethod returns a random port (this type of port is called an anonymous port ).

GetLocalPortThe method is defined as follows:

Public   Int GetLocalPort ()

GetLocalPortThe method is mainly for these anonymous ports. The following codeDemonstratedServerSocketThe process of generating random ports for objects:

Package Server;

Import Java.net. * ;

Public   Class RandomPort
{
Public   Static   Void Main (String [] args) Throws Exception
{
For ( Int I =   1 ; I <=   5 ; I ++ )
{
System. out. print ( " Random Port "   + I +   " : " );
System. out. println ( New ServerSocket ( 0 ). GetLocalPort ());
}
}
}

Running result:

Randport1: 1397
Random Port2: 1398
Random Port3: 1399
Random Port4: 1400
Random Port5: 1401

In most cases, the ServerSocket object is bound to a fixed port. However, sometimes the client only needs to connect to the server for a short period of time, then the anonymous port can be used. For example, we often use the FTP service.

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.