在套接字上指定源端口和目标端口 [英] specifying source and destination port on socket

查看:43
本文介绍了在套接字上指定源端口和目标端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 TCP 通信创建一个套接字,并想知道如何指定源端口.

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

Socket socket = new Socket();
socket.connect(dstAddress);

推荐答案

创建新的socket后,用你想要使用的本地端口号调用bind(),然后连接到远程主机.

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

@EJP 是正确的,不过.不要轻易执行此操作,因为如果其他东西碰巧正在使用该端口,或者即使您的程序最近使用了它并关闭了它,您最终可能无法创建套接字.

@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.

这篇关于在套接字上指定源端口和目标端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆