【发布时间】:2012-05-11 15:30:06
【问题描述】:
我不知道这是我处理 Android 的方式,还是我的本机代码有问题,或两者兼而有之。
我正在 C++ 中设置一个 udp 套接字(swig 生成的包装器):
udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (udpSocket < 0)
{
pthread_mutex_unlock(&csOpenCloseUdp);
throw IOException("Failed to open socket");
}
char bAllowMultiple = true;
setsockopt(udpSocket, SOL_SOCKET, SO_REUSEADDR, &bAllowMultiple, sizeof(bAllowMultiple));
setsockopt(udpSocket, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&hopLimit, sizeof(hopLimit));
setsockopt(udpSocket, IPPROTO_IP, IP_MULTICAST_IF, (char *)&localAddr, sizeof(localAddr));
// Set to non-blocking mode
unsigned long bMode = 1;
ioctl( udpSocket, FIONBIO, &bMode );
// Create the local endpoint
sockaddr_in localEndPoint;
localEndPoint.sin_family = AF_INET;
localEndPoint.sin_addr.s_addr = localAddr.s_addr;
localEndPoint.sin_port = groupEndPoint.sin_port;
// Bind the socket to the port
int r = bind(udpSocket, (sockaddr*)&localEndPoint, sizeof(localEndPoint));
if (r == SOCKET_ERROR)
{
//LeaveCriticalSection(&csOpenCloseUdp);
pthread_mutex_unlock(&csOpenCloseUdp);
close();
throw IOException("Failed to bind port");
}
// Join the multicast group
struct ip_mreq imr;
imr.imr_multiaddr = groupEndPoint.sin_addr;
imr.imr_interface.s_addr = localAddr.s_addr;
setsockopt(udpSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&imr, sizeof(imr));
套接字没有抛出任何异常,在此之后它的 some 值不是 INVALID_SOCKET。
当我尝试发送数据包时,
int r = sendto(udpSocket, (char*)dataToSend, (size_t)length, 0, (sockaddr*)&groupEndPoint, (socklen_t)sizeof(groupEndPoint));
我得到 errno 101:网络无法访问。
我对套接字编程很陌生,而且我知道 Android 中的套接字是一种不好的开始方式,但事实是我必须完成这项工作并且时间很少。这里有人知道导致网络无法访问的可能原因吗?有没有人尝试过在 Android 上使用 UDP 并能有所启发?
【问题讨论】:
-
造成这种情况的原因可能不在代码中,而在网络设置中。如果您在自己的私人 Wi-Fi 网络中,则应检查路由器设置。
-
我在 arm 开发板设备上使用物理 LAN。我将有一个直接从设备到它正在与之交谈的设备的专用链接。如果有人以前尝试过这种事情,我们将不胜感激
-
你能从 adb 命令行 ping 其他系统吗?
-
嗯。似乎没有。 Ping 到我的笔记本电脑的 IP 会返回无法从 adb shell 访问的网络。想法?
-
ip -s addr 显示 eth0: BROADCAST, MULTICAST mtu 1500 qdisc noop state DOWN qlen 1000 link/ether 08:90:00:a0:02:10 brd ff:ff:ff:ff:ff :ff
标签: android c++ sockets udp sendto