开发者

Can't receive UDP packet on android?

I tried to implement UDP server on Android, i can send packets to server, but can't received it. Also i tried run receiver without android, it works. Where is the problem?

Local sender for Testing:

int send_packet(uint8_t* data) {
    int retcode;
    int socket_out;
    int broadcast = 1;
    struct sockaddr_in addr;

    socket_out = socket(AF_INET, SOCK_DGRAM, 0);
    if ( socket_out < 0 )
        return -1;

    setsockopt(socket_out, SOL_SOCKET, SO_BROADCAST, &broadcast开发者_如何学C, sizeof broadcast);

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
    addr.sin_port=htons(PORT_NUMBER);

    retcode = sendto(socket_out, data, sizeof(packet_data_t), 0,
        (struct sockaddr *) &addr, sizeof(addr));
    perror("sendto");

    close(socket_out);

    return 0;
}

Android receiver:

public void run(){
   try {
       byte[] buffer = new byte[BUFFER_SIZE];
       DatagramSocket socket = new DatagramSocket(getPort());
       //socket.setBroadcast(true);
       while(true){
           DatagramPacket packet = new DatagramPacket(buffer, buffer.length );
           socket.receive(packet);
           (new CallbackWrapper(getPacketReciever())).run();
       }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

ps I am running my application on a HTC Legend, not on emulator


The main problem is on this line:

DatagramSocket socket = new DatagramSocket(getPort());

You are assuming that the local host of the device is the same as the machine/computer, but the device has got its own network card, consequently having his own IP in any network, and his own network address IP, which is his own. The device is not reachable through just a port of your machine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜