#include #include #include #include #include #include #include #include void DrukujNadawce(struct sockaddr_in *adres) // address - PrintSender { printf("Wiadomosc od (message from) %s:%d", //Message from %s:%d inet_ntoa(adres->sin_addr), ntohs(adres->sin_port) ); } void ObsluzTCP(int gniazdo, struct sockaddr_in *adres) //socket, address { int nowe_gniazdo; //new_socket char bufor[1024]; socklen_t dladr = sizeof(struct sockaddr_in); nowe_gniazdo = accept(gniazdo, (struct sockaddr*) adres, &dladr); if (nowe_gniazdo < 0) { printf("Bledne polaczenie (accept < 0)\n"); //invalid connection return; } memset(bufor, 0, 1024); while (recv(nowe_gniazdo, bufor, 1024, 0) <= 0); DrukujNadawce(adres); //PrintSender printf("[TCP]: %s\n", bufor); close(nowe_gniazdo); } void ObsluzUDP(int gniazdo, struct sockaddr_in *adres) //ServeUDP { char bufor[1024]; socklen_t dladr = sizeof(struct sockaddr_in); memset(bufor, 0, 1024); recvfrom(gniazdo, bufor, 1024, 0, (struct sockaddr*) adres, &dladr); DrukujNadawce(adres); printf("[UDP]: %s\n", bufor); //buffer } void ObsluzObaProtokoly(int gniazdoTCP, int gniazdoUDP, //serveBothProtocols(TCPSocket, UDPSocket) struct sockaddr_in *adres) { fd_set readfds; struct timeval timeout; unsigned long proba; //attempt/try int maxgniazdo; //maxSocket maxgniazdo = (gniazdoTCP > gniazdoUDP ? gniazdoTCP+1 : gniazdoUDP+1); proba = 0; while(1) { FD_ZERO(&readfds); FD_SET(gniazdoTCP, &readfds); FD_SET(gniazdoUDP, &readfds); timeout.tv_sec = 1; timeout.tv_usec = 0; if (select(maxgniazdo, &readfds, NULL, NULL, &timeout) > 0) { proba = 0; if (FD_ISSET(gniazdoTCP, &readfds)) ObsluzTCP(gniazdoTCP, adres); if (FD_ISSET(gniazdoUDP, &readfds)) ObsluzUDP(gniazdoUDP, adres); } else { proba++; printf("Czekam %lu sekund i nic ...\n", proba); //I'm wainting %lu seconds and nothing (happend) } } } int main(void) { struct sockaddr_in bind_me_here; int gt, gu, port; printf("Numer portu: "); scanf("%d", &port); gt = socket(PF_INET, SOCK_STREAM, 0); gu = socket(PF_INET, SOCK_DGRAM, 0); bind_me_here.sin_family = AF_INET; bind_me_here.sin_port = htons(port); bind_me_here.sin_addr.s_addr = INADDR_ANY; if (bind(gt,(struct sockaddr*) &bind_me_here, sizeof(struct sockaddr_in)) < 0) { printf("Bind na TCP nie powiodl sie.\n"); //TCP bind failed return 1; } if (bind(gu,(struct sockaddr*) &bind_me_here, sizeof(struct sockaddr_in)) < 0) { printf("Bind na UDP nie powiodl sie.\n"); //UDP bind failed return 1; } listen(gt, 10); ObsluzObaProtokoly(gt, gu, &bind_me_here); //serveBothProtocols return 0; }