udp tcp epoll serv
[socket_samples.git] / client_udp.c
blob46b346aa94a4deb4f6e346ff4d9908ed0a4b91c9
1 /* UDP client in the internet domain */
2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <netinet/in.h>
5 #include <arpa/inet.h>
6 #include <netdb.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <string.h>
12 void error(const char *);
13 int main(int argc, char *argv[])
15 int sock, n;
16 unsigned int length;
17 struct sockaddr_in server, from;
18 struct hostent *hp;
19 char buffer[256];
21 if (argc != 3) { printf("Usage: server port\n");
22 exit(1);
24 sock= socket(AF_INET, SOCK_DGRAM, 0);
25 if (sock < 0) error("socket");
27 server.sin_family = AF_INET;
28 hp = gethostbyname(argv[1]);
29 if (hp==0) error("Unknown host");
31 bcopy((char *)hp->h_addr,
32 (char *)&server.sin_addr,
33 hp->h_length);
34 server.sin_port = htons(atoi(argv[2]));
35 length=sizeof(struct sockaddr_in);
36 printf("Please enter the message: ");
37 while(1){
38 bzero(buffer,256);
39 fgets(buffer,255,stdin);
40 n=sendto(sock,buffer,
41 strlen(buffer),0,(const struct sockaddr *)&server,length);
42 if (n < 0) error("Sendto");
43 n = recvfrom(sock,buffer,256,0,(struct sockaddr *)&from, &length);
44 if (n < 0) error("recvfrom");
45 write(1,"Got an ack: ",12);
46 write(1,buffer,n);
48 close(sock);
49 return 0;
52 void error(const char *msg)
54 perror(msg);
55 exit(0);