Diferenças
Aqui você vê as diferenças entre duas revisões dessa página.
Ambos lados da revisão anterior Revisão anterior | |||
pua:cliente_udp [2014/03/27 12:19] – maziero | pua:cliente_udp [2014/03/28 18:16] (atual) – maziero | ||
---|---|---|---|
Linha 1: | Linha 1: | ||
+ | ====== Exemplo UDP: Port talker ====== | ||
+ | |||
+ | Este exemplo implementa um cliente UDP que envia um pacote contendo uma mensagem à porta UDP 4950 de um servidor. | ||
+ | |||
+ | <code c talker.c> | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | |||
+ | // receiver listening port | ||
+ | #define RCVR_PORT 4950 | ||
+ | |||
+ | int main(int argc, char *argv[]) | ||
+ | { | ||
+ | int sockfd; | ||
+ | struct sockaddr_in rcvr_addr; | ||
+ | struct hostent *he; | ||
+ | int numbytes; | ||
+ | |||
+ | if (argc != 3) | ||
+ | { | ||
+ | fprintf(stderr," | ||
+ | exit(1); | ||
+ | } | ||
+ | |||
+ | // translates receiver name to address | ||
+ | he = gethostbyname(argv[1]) ; | ||
+ | if (he == NULL) | ||
+ | { | ||
+ | perror(" | ||
+ | exit(1); | ||
+ | } | ||
+ | |||
+ | // fills the receiver struct info | ||
+ | rcvr_addr.sin_family = AF_INET; | ||
+ | rcvr_addr.sin_port | ||
+ | rcvr_addr.sin_addr | ||
+ | |||
+ | // zeroes the rest of the struct | ||
+ | memset(& | ||
+ | |||
+ | // creates the UDP socket | ||
+ | sockfd = socket (AF_INET, SOCK_DGRAM, 0) ; | ||
+ | if (sockfd == -1) | ||
+ | { | ||
+ | perror(" | ||
+ | exit(1); | ||
+ | } | ||
+ | |||
+ | // sends the message to the receiver using the socket | ||
+ | numbytes = sendto (sockfd, argv[2], strlen(argv[2]), | ||
+ | | ||
+ | | ||
+ | if (numbytes == -1) | ||
+ | { | ||
+ | perror(" | ||
+ | exit(1); | ||
+ | } | ||
+ | |||
+ | printf ("sent %d bytes to host %s port %d\n", numbytes, | ||
+ | inet_ntoa (rcvr_addr.sin_addr), | ||
+ | |||
+ | // closes the socket | ||
+ | close (sockfd); | ||
+ | |||
+ | return 0; | ||
+ | } | ||
+ | </ | ||