By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,805 Members | 1,392 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,805 IT Pros & Developers. It's quick & easy.

Is port no. necessary in networking through URL class?

P: 7
In the following code:

Expand|Select|Wrap|Line Numbers
  1. public class URLDemo {
  2.        public static void main(String args[])throws Exception {
  3.             URL u=new URL("http://www.google.com");
  4.             System.out.println("Port No : "+u.getPort());
  5.           }
  6.        }
  7.  
I haven't explicitly specified the Port No. in the URL above, but is it so "that port nos. ain't necessary"
Also the above program gives me the output "-1" so
1. Is there a default port automatically assigned by Java?(i heard it is "80")
2. If YES then why did the output render(display) "-1".
Mar 27 '13 #1
Share this Question
Share on Google+
7 Replies


10K+
P: 13,264
The default port is set according to the protocol. You can print out u.getDefaultPort() to see what the default is.
You should read your earlier thread on sockets to understand how ports are assigned.
Mar 27 '13 #2

P: 7
So what if I specify the port 23 and the protocol as HTTP
as in case of,
Expand|Select|Wrap|Line Numbers
  1. URL u=new URL("http://www.osborne.com:23/index.html");
  2.  
Sorry to say but i was enable to get your point in the previous thread!!!
Mar 27 '13 #3

P: 7
And you didn't explain me "why the program outputs -1"
Mar 27 '13 #4

10K+
P: 13,264
You need to read up on basic computer networking first before looking at the Java API that uses it otherwise everything won't make sense.
Mar 27 '13 #5

Rabbit
Expert Mod 10K+
P: 12,422
Post #1
1. The default port for http is 80.
2. You did not explicitly define a port. When you don't explicitly define a port, it returns -1.

Post #5
You can specify the port like that in your URL if you want. It won't connect to anything because the server probably uses port 80. But you can explicitly define the port that way.
Mar 27 '13 #6

P: 7
So if I don't specify the port no. "The Output will be -1. but the port that will be used to access the resource will be 80 i.e HTTP". Am i correct?
Apr 8 '13 #7

10K+
P: 13,264
As I said above, the defaultPort will still be assigned (by the HTTP handler) to 80 whether you specified a port or not. You still don't seem to understand the difference between those two.
Apr 8 '13 #8

Post your reply

Sign in to post your reply or Sign up for a free account.