英文:
Java set different IP address on DatagramSocket
问题
我想在我的计算机上模拟一个网络。
我希望每个数据包都使用不同的IP地址发送。
如何在套接字上设置IP地址?
例如,我希望将我的IP地址设置为192.168.1.1或192.168.1.1/24。
我应该如何操作?
我只知道如何设置端口号。
private static DatagramSocket socket;
socket = new DatagramSocket(1024);
我可以使用
DatagramSocket(int port, InetAddress laddr)
来初始化我的套接字吗?
如果可以,我应该在参数"laddr"中输入什么?
英文:
I want to simulate a network on my computer.
I want to send each packet with a different IP address.
How do I set the IP address on the Socket?
For example, I want to set my IP address is 192.168.1.1 or 192.168.1.1/24.
How do I do?
I only know how to set the port number.
private static DatagramSocket socket;
socket = new DatagramSocket(1024);
Can I use
DatagramSocket(int port, InetAddress laddr)
to initial my socket?
if yes, what should I input in the parameter "laddr"?
答案1
得分: 1
假设你的意思是设置源IP地址 - 你是不能这么做的。一个UDP套接字会绑定到计算机上特定的IP接口(或接口)。IP接口才“拥有”地址。使用IP套接字的程序只能选择使用已有的接口。
请注意,即使你能在传出的数据报中任意设置源地址字段,也没有简单的方法来接收任何回复 - 因为在你的计算机上没有任何东西响应你选择的地址(该地址上没有IP接口)。
如果你想在程序中模拟不同的IP地址,你需要模拟IP。这将涉及使用原始套接字,但似乎没有Java的实现方法。
英文:
Assuming you mean set the source IP address - you can't. A UDP socket is bound to a particular IP interface (or interfaces) on your computer. The IP interface is what 'has' the address. A program using IP sockets only gets to choose which existing interface to use.
Note that even if you could arbitrarily set the source-address field in an outgoing datagram, there would be no simple way to receive any reply - because there's nothing on your computer responding to your chosen address (there is no IP interface at that address).
If you want to simulate having different IP addresses in a program,, you'll need to simulate IP. That would involve using raw sockets, but there does not seem to be a Java implementation for that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论