Stefan
Stefan

Reputation: 1059

How can Socket object be made with ServerSocket's method accept()?

After finishing I/O streams and Concurrency I decided to learn Socket programming. So far I made a simple Server-Client. But I have a little question about understanding how are Socket objects actually made. Hope someone can make an easy explanation, as I am new to this.

The basic rule I follow is to make Socket by providing both IP Address and Port number. So I would do something like:

Socket s = new Socket(StringIP, intPort);

But I also came across the thing that confuses me, and that is using accept() from ServerSocket's class.

ServerSocket myServer = new ServerSocket(portNum);
Socket socket = myServer.accept();

Doc says it returns new Socket after a connection is made. Fair enough. But how can it know the client's port and IP? Does it mean that the variable socket has all the data about the client (meaning on its IP and port)? If so, how can it know it, without me manually putting it in the constructor as I showed in the first example? Can someone tell me what am I missing so I can move on?

Upvotes: 0

Views: 154

Answers (1)

Stephen C
Stephen C

Reputation: 718946

But how can it know the client's port and IP?

The client port and IP are in the network packets. The operating system picks up and records this information, and passes it on to Java via the results (loosely speaking) of syscalls. This is all done under the hood in JVM native code. (And the OS kernel, of course.)

If you really need to understand exactly how this happens, it will all be clear in the OpenJDK source code (which is freely downloadable). But you would need to be able to read and search C and C++ code to figure it out.

Upvotes: 1

Related Questions