2014-05-18 8 views
6

Vorrei inviare e ricevere pacchetti sullo stesso socket, è possibile o devo creare due socket, uno da inviare e uno da ricevere? Se sì, puoi darmi un esempio?c - udp invia e riceve sulla stessa presa

Un'altra domanda: come posso ottenere l'ip sorgente da un pacchetto ricevuto?

EDIT (esempio di codice):

int main(void) { 
    struct sockaddr_in si_me, si_other; 
    int s, i, slen=sizeof(si_other); 
    char buf[BUFLEN]; 

    if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) 
     die("socket"); 

    memset((char *) &si_me, 0, sizeof(si_me)); 
    si_me.sin_family = AF_INET; 
    si_me.sin_port = htons(1234); 
    si_me.sin_addr.s_addr = htonl(192.168.1.1); 

    if (bind(s, &si_me, sizeof(si_me))==-1) 
     die("bind"); 

    if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1) 
     diep("recvfrom()"); 
    printf("Data: %s \nReceived from %s:%d\n\n", buf, inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); 

    //now I want the server to answer back to the client 

    close(s); 
    return 0; 
} 

risposta

12

Sì, è possibile utilizzare lo stesso socket per inviare e ricevere. recvfrom() indica l'IP/porta del mittente. Semplicemente sendto() che IP/porta tramite la stessa presa che si utilizza con recvfrom(), ad esempio:

int main(void) { 
    struct sockaddr_in si_me, si_other; 
    int s, i, blen, slen = sizeof(si_other); 
    char buf[BUFLEN]; 

    s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 
    if (s == -1) 
     die("socket"); 

    memset((char *) &si_me, 0, sizeof(si_me)); 
    si_me.sin_family = AF_INET; 
    si_me.sin_port = htons(1234); 
    si_me.sin_addr.s_addr = htonl(192.168.1.1); 

    if (bind(s, (struct sockaddr*) &si_me, sizeof(si_me))==-1) 
     die("bind"); 

    int blen = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*) &si_other, &slen); 
    if (blen == -1) 
     diep("recvfrom()"); 

    printf("Data: %.*s \nReceived from %s:%d\n\n", blen, buf, inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); 

    //send answer back to the client 
    if (sendto(s, buf, blen, 0, (struct sockaddr*) &si_other, slen) == -1) 
     diep("sendto()"); 

    close(s); 
    return 0; 
} 
+0

possibile inviare prego un esempio? – user3574984

+0

Di cosa? invio/ricezione? O ottenendo l'IP/Port sorgente? Ci sono molti esempi di entrambi online se ti guardi intorno. –

+0

Il server riceve un pacchetto => risponde allo stesso socket udp ... so come ricevere e come inviare, ma non come farlo con lo stesso socket! – user3574984

Problemi correlati