java中的小型ip扫描器代码
我正在用java编写一个小游戏。有一个服务器和一个客户端模块。目前,每个客户端都必须手动输入服务器 IP(在本地网络中)。这就是我在这里编写这段代码的原因:
import java.net.*;
public class myIP {
public static void main (String argv[])
{
try{
InetAddress ownIP=InetAddress.getLocalHost();
String myIP = ownIP.getHostAddress();
System.out.println( "IP of my system is := "+ myIP );
}catch (Exception e){
System.out.println( "Exception caught ="+e.getMessage() );
}
}
}
这段代码返回机器的 IP 地址。有了这些信息(我自己的 IP 地址),我现在想检查此范围内的其他 IP 地址,以自动查找服务器。
现在我不知道如何迭代这个IP范围。例如:如果“myIP”是 10.0.0.5,我如何修改该字符串,以便我拥有 10.0.0.6?如果它是一个整数值,那么每次加 1 都会很容易 - 但因为它是一个字符串 - 用点分隔 - 我不知道如何解决这个问题:) 有什么想法吗?
干杯
I'm writing a small game in java. There's a server and a client module. At the moment every client has to enter the server IP (in a local network) manually. Thats why I have written this code here:
import java.net.*;
public class myIP {
public static void main (String argv[])
{
try{
InetAddress ownIP=InetAddress.getLocalHost();
String myIP = ownIP.getHostAddress();
System.out.println( "IP of my system is := "+ myIP );
}catch (Exception e){
System.out.println( "Exception caught ="+e.getMessage() );
}
}
}
This piece of code returns the IP address of the machine. With this information (my own IP address) I'd like to check now for other IP addresses in this range to find the server automatically.
Now I don't know how to iterate over this IP range. For example: if "myIP" is 10.0.0.5, how can I modify that string so I would have 10.0.0.6 for example? If it would be an integer value, it would be easy to add 1 every time - but since it's a string - separated by dots - I'm not sure how to solve that :) any idea?
cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这往往通过广播/组播来实现。这不是我玩过的东西,所以不能为您提供任何代码,但是 this链接提供了很好的解释。
编辑:它超越了 MulticastSocket 您也许可以使用的课程。
This tends to be achieved using broadcast/multicast. This is not something I have ever played with so can not offer you any code, but this link offers a good explanation.
Edit: it transcends there is a MulticastSocket class which you may be able to put to use.
因此,您需要将 IPv4 地址与 Int 地址相互转换。
看看这是否有帮助:
http:// /teneo.wordpress.com/2008/12/23/java-ip-address-to-integer-and-back/
So, what you need is to convert an IPv4 address to Int and back.
See if this helps:
http://teneo.wordpress.com/2008/12/23/java-ip-address-to-integer-and-back/
您应该使用
getAddress
来返回 ip 作为字节数组,而不是getHostAdress
。You should you
getAddress
which returns ip as byte array instead ofgetHostAdress
.以下是来自 TechnoJeeves 的代码示例,用于执行此操作。
Here is the code sample from TechnoJeeves to do this.