1 Example (UDP Client) // This program sends UDP packets to the given address #include #define SERVER_ADDR " " #define SERVER_PORT 5555 void error(char *str) { printf("\n%s", str); exit(0); } int main(int argc, char *argv[]) { char message[100], message2[10]; int sockfd, res; struct sockaddr_in client_addr, server_addr; int i, mesNum; printf("\nClient is running..."); if (argc < 2) error("\nYou should supply parameter: the number of messages to send");
2 Example (UDP Client) // Opening socket if ((sockfd = socket (AF_INET, SOCK_DGRAM, 0)) < 0) error("Could not open socket"); // Sending a message to the server bzero((char*) &server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(SERVER_ADDR); server_addr.sin_port = htons(SERVER_PORT); mesNum = atoi(argv[1]); if (mesNum == 0) error("\nIllegal parameter"); for (i=0; i<mesNum; i++) { strcpy(message, "Test message: "); sprintf(message2, "%d", i+mesNum); strcat(message, message2); res = sendto (sockfd, message, strlen(message)+1, 0, (struct sockaddr*)&server_addr, sizeof(server_addr)); printf("\nClient sent %d bytes", res); }
3 Example (UDP Server) // This program receives UDP packets #include #define SERVER_PORT 5555 #define MAX_MESSAGE_SIZE 100 void error(char *str) { printf("\n%s", str); exit(0); } int main() { char message[MAX_MESSAGE_SIZE]; int sockfd, res; struct sockaddr_in client_addr, server_addr; int addr_len; printf("\nServer is running..."); fflush(stdout);
4 Example (UDP Server) // Opening socket if ((sockfd = socket (AF_INET, SOCK_DGRAM, 0)) < 0) error("Could not open socket"); // Bind local ip and process addresses bzero((char*) &server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(SERVER_PORT); if ( bind (sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) error("Could not bind to the socket"); while (1) { // Receiving a message from the client addr_len = sizeof(client_addr); res = recvfrom (sockfd, message, MAX_MESSAGE_SIZE, 0, (struct sockaddr*)&client_addr, &addr_len); printf("\nServer received %d bytes", res); printf("\n%s", message); fflush(stdout); }