开发者

specifying source and destination port on socket

I am creating a socket for TCP communication and would like to know how to specify a source port.

Socket socket = 开发者_Go百科new Socket();
socket.connect(dstAddress);


After creating your new socket, call bind() with the local port number you want to use, then connect to the remote host.

@EJP is correct, though. Don't do this lightly since you can end up not being able to create the socket if something else happens to be using that port or even if your program has recently used it and closed it.

If it's not working, you may need to look at the library you're using.


Socket has multiple constructors. Try this one


You have to use InetSocketAddress, declared in the package java.net. The easiest way to use it is:

InetSocketAddress(host, port)), something like this:

Socket socket = new Socket();
socket.connect(new InetSocketAddress("http://myserver.com", 80));

Which connect to the web server listening on the port 80 in myserver.com.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜