涉及 Java 的 RAW 套接字编程的最佳方法

发布于 2024-09-26 03:45:07 字数 615 浏览 3 评论 0原文

我有一些现有的 C 代码使用 ICMP 原始套接字来执行 Ping,并且我需要在 Java 中使用此代码,因为 Java 不支持 ICMP 包。当我将代码包装在JNI中并调用它时,C代码在执行以下操作时无法获取套接字:

socket(AF_INET, SOCK_RAW, 1);

我猜想 Java 已经放弃了一些特权,禁止在 Java 进程中使用原始套接字。这个我必须想办法解决。

我观察到以下情况:

  • 如果我编写一个 C 程序并使用运行时从 Java 调用该程序,则分叉代码可能会打开套接字。
  • 如果我从 Eclipse 运行这个本机代码,它也运行得很好。我想这是因为 Eclipse 是从 eclipse.exe 启动的,而不是从 java.exe 启动的。

这意味着我可以通过选择这两种策略之一来解决我的问题,但我都不喜欢。有没有其他方法可以让 Java 接受 JNI 代码正在打开此套接字?

编辑: 我越深入地研究这个问题,我发现它一定是与 Windows 7 相关的 Java 启动方式问题。

如果您让 Windows 正常运行,或者您使用的是 Windows 以外的其他平台,则也可以使用 InetAddress.isReachable() 方法。

I have some existing C code that uses ICMP raw sockets to do Ping and I need to use this code in Java as Java does not support ICMP packages. When I wrap the code in JNI and call it, the C code fails to obtain the socket when doing:

socket(AF_INET, SOCK_RAW, 1);

I guess that Java has dropped some privileges that disables the use of raw socket from the Java process. This I must find a solution to.

I have observed the following:

  • If I write a C program and call that from Java using Runtime the forked code may open the socket.
  • If I run this native code from Eclipse it also runs nicely. I guess this comes from the fact that Eclipse has been started from eclipse.exe, and not from java.exe.

This means that I could solve my problem by choosing one of these two strategies, but I like neither. Are there any other ways that I could get Java to accept that the JNI code is opening this socket?

Edit:
The more I look into this problem I figure that it must be a windows 7 related issue with how Java is being started.

It also appears that if you get windows to behave or if you are on some other platform than Windows the method InetAddress.isReachable() could be used as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等风来 2024-10-03 03:45:07

也许使用现有的 Java 本机套接字库?那么您就不必担心 JNI 库的编码问题。

请参阅:http://www.savarese.com/software/rocksaw/

Maybe use an existing Java native socket lib? Then you don't have to worry about coding the JNI lib.

See: http://www.savarese.com/software/rocksaw/

残疾 2024-10-03 03:45:07

您不妨尝试一下 java.net.InetAddress.isReachable() 方法,该方法从 J2SE5 开始可用。

但它在 Windows 中并没有按预期工作。请参阅:http://bordet.blogspot.com/2006/07/icmp -and-inetaddressisreachable.html

You might as well try the java.net.InetAddress.isReachable()method, this is available from J2SE5 onwards.

But it is not working as expected in Windows. See: http://bordet.blogspot.com/2006/07/icmp-and-inetaddressisreachable.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文