我有一个用C ++编写的服务器,它将使用此代码在网络上发送UDP广播(将代码减少到所需的最低数量,因此此处可能存在一两个语法错误):
bool open_socket()
{
sockfd_ = ::socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0);
if (sockfd_ == -1)
{
logger_.error("Error creating socket (%d).", errno);
return false;
}
int bc = broadcast ? 1 : 0;
if (::setsockopt(sockfd_, SOL_SOCKET, SO_BROADCAST, (void *)&bc, sizeof(bc)) < 0)
{
logger_.error("Could not set broadcast option.");
return false;
}
else
{
is_broadcast_ = broadcast;
}
return true;
}
int write_to_socket(const std::string &address, uint16_t port, uint8_t *buffer, int bufsize)
{
struct hostent *h = ::gethostbyname(address.c_str());
if (!h)
{
logger_.error("Could not resolve %s", address.c_str());
return 0;
}
struct sockaddr_in remote_server;
::memset(&remote_server, 0, sizeof(remote_server));
remote_server.sin_family = h->h_addrtype;
remote_server.sin_port = htons(port);
::memcpy ( (char *) &remote_server.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
int res = ::sendto(sockfd_, buffer, bufsize, 0, (struct sockaddr *)&remote_server, sizeof(remote_server));
if (res == -1)
{
logger_.error("Could not send to \"%s\" (%d)", address.c_str(), errno);
}
return res;
}
我将代码用于:
socket_.write("192.168.42.255", 18997, (uint8_t *)magic_packet_.c_str(), magic_packet_.size() + 1);
其中magic_packet_
是值std::string
的{{1}};
使用此代码时,我可以看到该软件包正确出现在wirehark中。其他C ++程序也可以接收广播,因此我认为代码可以正常工作。
现在我有一个Android应用程序,它将接收所述广播数据包。事实是该软件包将不会显示,并且SPCCBC
函数将无限期阻塞。这是代码(请注意,这是在不同于主线程的另一个线程上执行的!):
receive
Android设备位于同一网络中,并且IP地址在此范围内(该设备具有package net.dev_shack.silentplayerpartyclient;
import android.util.Log;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicBoolean;
public class UdpBroadcastListener extends Thread
{
private DatagramSocket socket;
AtomicBoolean running = new AtomicBoolean(false);
@Override
public void run() {
synchronized (this)
{
try {
socket = new DatagramSocket(18997);//, InetAddress.getByName("0.0.0.0"));
}
catch (SocketException e) {
Log.e("UdpBroadcastListener", "Could not create DatagramListenSocket");
notify();
e.printStackTrace();
return;
}
/*catch (UnknownHostException e) {
notify();
e.printStackTrace();
return;
}*/
running.set(true);
notify();
}
while (running.get())
{
byte[] message = new byte[1500];
DatagramPacket packet = new DatagramPacket(message, message.length);
try {
socket.receive(packet);
} catch (IOException e) {
continue;
}
Log.i("UdpBroadcastReceiver", "Got: " + packet.toString());
}
}
public void stop_listener() {
running.set(false);
if (socket != null) {
socket.close();
}
}
}
,发送方具有192.168.42.116
,网络是192.168.42.5
,其网络掩码为{{1 }}。
java代码是否有问题?请注意注释为192.168.42.0
的注释,无论是否使用,我都尝试过。