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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3854961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:42:22  来源:igfitidea点击:

Best way to do RAW socket programming involving Java

javacnetworkingjava-native-interface

提问by Knubo

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:

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

socket(AF_INET, SOCK_RAW, 1);

套接字(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.

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

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

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

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.

编辑:我对这个问题的研究越多,我认为它一定是与 Java 启动方式有关的 Windows 7 相关问题。

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.

看来,如果您让 Windows 运行起来,或者如果您在 Windows 以外的其他平台上,也可以使用 InetAddress.isReachable() 方法。

采纳答案by Andy

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

也许使用现有的 Java 本机套接字库?然后您不必担心对 JNI 库进行编码。

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

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

回答by Muthuvel

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

您不妨试试该java.net.InetAddress.isReachable()方法,从 J2SE5 开始就可以使用该方法。

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

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