This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
zhangyang-libzt/tests/udp_client.c

93 lines
2.3 KiB
C
Raw Normal View History

2016-08-11 23:30:58 -07:00
/*
* udpclient.c - A simple UDP client
* usage: udpclient <host> <port>
*/
2016-06-27 15:50:03 -07:00
#include <stdio.h>
2016-08-11 23:30:58 -07:00
#include <stdlib.h>
2016-06-27 16:25:50 -07:00
#include <string.h>
2016-08-11 23:30:58 -07:00
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
2016-06-27 15:50:03 -07:00
2016-08-11 23:30:58 -07:00
#define BUFSIZE 1024
2016-07-18 12:24:24 -07:00
2016-08-11 23:30:58 -07:00
/*
* error - wrapper for perror
*/
void error(char *msg) {
perror(msg);
exit(0);
}
int main(int argc, char **argv) {
int sockfd, portno, n;
int serverlen;
struct sockaddr_in serveraddr;
struct hostent *server;
char *hostname;
char buf[BUFSIZE];
/* check command line arguments */
if (argc != 3) {
fprintf(stderr,"usage: %s <hostname> <port>\n", argv[0]);
exit(0);
}
2016-08-11 23:30:58 -07:00
hostname = argv[1];
portno = atoi(argv[2]);
/* socket: create the socket */
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
2016-06-27 15:50:03 -07:00
2016-08-11 23:30:58 -07:00
/* gethostbyname: get the server's DNS entry */
server = gethostbyname(hostname);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host as %s\n", hostname);
exit(0);
2016-06-27 15:50:03 -07:00
}
2016-08-11 23:30:58 -07:00
/* build the server's Internet address */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(portno);
/* get a message from the user */
char *msg = "A message to the server!\0";
fcntl(sockfd, F_SETFL, O_NONBLOCK);
long count = 0;
while(1)
{
2016-06-27 15:59:07 -07:00
count++;
2016-08-11 23:30:58 -07:00
printf("\nTX(%lu)...\n", count);
usleep(100000);
//bzero(buf, BUFSIZE);
//printf("\nPlease enter msg: ");
//fgets(buf, BUFSIZE, stdin);
2016-06-27 15:50:03 -07:00
2016-08-11 23:30:58 -07:00
/* send the message to the server */
serverlen = sizeof(serveraddr);
printf("A\n");
n = sendto(sockfd, msg, strlen(msg), 0, &serveraddr, serverlen);
printf("B\n");
//if (n < 0)
// error("ERROR in sendto");
/* print the server's reply */
printf("C\n");
memset(buf, 0, sizeof(buf));
printf("D\n");
n = recvfrom(sockfd, buf, BUFSIZE, 0, &serveraddr, &serverlen);
printf("E\n");
//if (n < 0)
// printf("ERROR in recvfrom: %d", n);
printf("Echo from server: %s", buf);
2016-06-27 15:50:03 -07:00
}
2016-08-11 23:30:58 -07:00
return 0;
2016-06-27 15:50:03 -07:00
}