【问题标题】:Android BSD sockets connectionAndroid BSD 套接字连接
【发布时间】:2015-01-09 06:47:01
【问题描述】:

我在尝试将 BSD 客户端套接字连接到服务器时遇到了一些问题。 套接字创建和连接是用 JNI 实现的。实际的连接是通过java代码建立的。

JNI 部分:

#include <jni.h>

#include <unistd.h>
#include <string.h>

#include <sys/endian.h>
#include <sys/ioctl.h>

#include <sys/errno.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <netinet/in.h>

JNIEXPORT jint JNICALL Java_com_example_socketclinet_Native_socket
(JNIEnv *, jclass, jint, jint, jint);

JNIEXPORT jint JNICALL Java_com_example_socketclinet_Native_connect
(JNIEnv *, jclass, jint, jint, jint);

jint JNICALL Java_com_example_socketclinet_Native_socket
(JNIEnv *env, jclass cls, jint domain, jint type, jint protocol)
{
    return socket(domain, type, protocol);
}

jint JNICALL Java_com_example_socketclinet_Native_connect
(JNIEnv *env, jclass cls, jint socket, jint address, jint port)
{
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(struct sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(address);
    addr.sin_port = htons(port);
    return connect(socket, (const struct sockaddr *)&addr, sizeof(struct sockaddr_in));
}

Java 原生桥接类:

class Native
{
    static
    {
        System.loadLibrary("mylib");
    }

    public static final int SOCK_STREAM = 2;
    public static final int AF_INET = 2;

    public static native int socket(int domain, int type, int protocol);
    public static native int connect(int socket, int address, int port);
}

原生类用法:

int socket = Native.socket(Native.AF_INET, Native.SOCK_STREAM, 0);
if (socket < 0)
{
    System.err.println("Socket error: " + socket);
    return;
}

byte[] address = { .... }; // 192.168.xxx.xxx
int addr = address[0] << 24 | address[1] << 16 | address[2] << 8 | address[3];
int port = ....;

int result = Native.connect(socket, addr, port);
if (result < 0)
{
    System.err.println("Connection failed: " + result);
}
else
{
    System.out.println("Connected");
}

即使没有服务器在运行(在设备和模拟器上),“connect”方法也总是返回“0”。

• 我在清单文件中设置了“INTERNET”权限(没有它,“socket”函数返回 -1)
• 相同的代码在 iOS 和 Mac OS 上运行良好。
• 测试环境:Nexus 5 (4.4.4), android-ndk-r10d

任何帮助将不胜感激!

【问题讨论】:

    标签: java android sockets android-ndk java-native-interface


    【解决方案1】:

    byte[] 是用 Java 签名的,这意味着你的 |addr|计算很可能是错误的。我怀疑您正在连接到广播地址,根据定义,它总是会成功。

    尝试从本机代码打印地址以验证是否,否则,尝试将计算替换为:

    int addr = (address[0] & 255) << 24 | 
               (address[1] & 255) << 16 |
               (address[2] & 255) <<  8 |
               (address[3] & 255);
    

    看看能不能解决问题。

    【讨论】:

    • 您无法将 TCP 套接字连接到广播地址。
    • @Digit,它不起作用。此外,尝试在本机代码中硬编码地址 - 不走运。我最终在 java 中编写了套接字通信代码并添加了一个 JNI 绑定(就像一个魅力一样工作)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 2013-12-26
    相关资源
    最近更新 更多