In problema de mai jos, un client UDP trimite unui server toate numerele de la 1 la 10000. Serverul primeste numerele si afiseaza un mesaj de fiecare data cand primeste un numar “out of order”. Acest lucru se intampla deoarece protocolul UDP nu este orientat pe conexiune si nu face validari si verificari in ceea ce priveste trimiterea/receptionarea pachetelor care pot sa soseasca la receptor in alta ordine fata de ordinea in care au fost trimise, sau frecvent, chiar sa se piarda.
clientUDP.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <netinet/ip.h> #include <string.h> int main() { int c; struct sockaddr_in server; uint16_t a, b, suma, i, k; c = socket(AF_INET, SOCK_DGRAM, 0); if (c < 0) { printf("Eroare la crearea socketului client\n"); return 1; } memset(&server, 0, sizeof(server)); server.sin_port = htons(1234); server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr("172.30.0.3"); for (i = 0; i < 10000; i++) { k = i + 1; k = htons(k); sendto(c, &k, sizeof(k), 0, (struct sockaddr *) &server, sizeof(server)); } close(c); } |
serverUDP.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <netinet/ip.h> #include <string.h> int main() { int s; struct sockaddr_in server, client; int c, l, i; uint16_t k, old = 0; s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { printf("Eroare la crearea socketului server\n"); return 1; } memset(&server, 0, sizeof(server)); server.sin_port = htons(1234); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; if (bind(s, (struct sockaddr *) &server, sizeof(server)) < 0) { printf("Eroare la bind\n"); return 1; } l = sizeof(client); memset(&client, 0, sizeof(client)); for (i = 0; i < 10000; i++) { recvfrom(s, &k, sizeof(k), MSG_WAITALL, (struct sockaddr *) &client, &l); k = ntohs(k); // printf("Am primit: %hu la pasul %d\n", k, i+1); if (k != old + 1) printf("Am primit aiurea pe %hu\n", k); old = k; } close(s); } |