navyad
navyad

Reputation: 3860

port in URL constructor

I want to check which port is used, when the port is not explicitly specified in the URL constuctor. SO here is a code.

 URL url = new URL("http://www.ietf.org/rfc/rfc2396.txt");
    System.out.println("URL :"+url.getPort());

getPort() returned -1. It indicates that I have not set the port thats why grtPort() had returned the -1 value.

In java doc of java.net.URL class

"If the port is not specified in URL, the default port for the protocol is used instead. The default port for http is 80."

Then in the above case it should have returned the 80 default port. Isn't it ? But it is not. So how do I know which port is being used for the connection?

Upvotes: 4

Views: 5034

Answers (4)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

See this example gives default ports for their respective services. I have shown http, and ftp here.

Eg:

public class Test {

public static void main(String[] args){



try {
System.out.println(new URL("http://www.ietf.org/rfc/rfc2396.txt").getDefaultPort());

System.out.println(new URL("ftp://www.ietf.org/rfc/rfc2396.txt").getDefaultPort());


        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Upvotes: 3

Chakravyooh
Chakravyooh

Reputation: 117

It depends on Which kind of request you are sending.

the default ports for different protocols are different.

20 & 21: File Transfer Protocol (FTP)
22: Secure Shell (SSH)
23: Telnet remote login service
25: Simple Mail Transfer Protocol (SMTP)
53: Domain Name System (DNS) service
80: Hypertext Transfer Protocol (HTTP) used in the World Wide Web
110: Post Office Protocol (POP3)
119: Network News Transfer Protocol (NNTP)
143: Internet Message Access Protocol (IMAP)
161: Simple Network Management Protocol (SNMP)
443: HTTP Secure (HTTPS)

Upvotes: 0

subodh
subodh

Reputation: 6158

To get default pot there is a method getDefaultPort() inside java.net.URL class

use this

int port  = new URL("http://www.ietf.org/rfc/rfc2396.txt").getDefaultPort();

Upvotes: 1

Talon876
Talon876

Reputation: 1492

You want url.getDefaultPort().

Upvotes: 0

Related Questions