client.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 |
#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; c = socket(AF_INET, SOCK_STREAM, 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("127.0.0.1"); if (connect(c, (struct sockaddr *) &server, sizeof(server)) < 0) { printf("Eroare la conectarea la server\n"); return 1; } printf("a = "); scanf("%hu", &a); printf("b = "); scanf("%hu", &b); a = htons(a); b = htons(b); send(c, &a, sizeof(a), 0); send(c, &b, sizeof(b), 0); recv(c, &suma, sizeof(suma), 0); suma = ntohs(suma); printf("Suma este %hu\n", suma); close(c); } |
server.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 44 45 46 47 48 49 |
#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; s = socket(AF_INET, SOCK_STREAM, 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; } listen(s, 5); l = sizeof(client); memset(&client, 0, sizeof(client)); while (1) { uint16_t a, b, suma; c = accept(s, (struct sockaddr *) &client, &l); printf("S-a conectat un client.\n"); // deservirea clientului recv(c, &a, sizeof(a), MSG_WAITALL); recv(c, &b, sizeof(b), MSG_WAITALL); a = ntohs(a); b = ntohs(b); suma = a + b; suma = htons(suma); send(c, &suma, sizeof(suma), 0); close(c); // sfarsitul deservirii clientului; } } |