char msg[257]; struct sockaddr_in sourcesa, targetsa; int ssize = sizeof(sourcesa);The usual ways to call sendto and recvfrom are:
int s = sendto(sfd,msg,strlen(msg),0,(struct sockaddr*)&targetsa,sizeof(targetsa)); int r = recvfrom(sfd,msg,256,0,(struct sockaddr*)&sourcesa,&ssize);explain why calling recvfrom like this
recvfrom(sfd,msg,256,0,NULL,NULL);is OK, but calling sendto like this
sendto(sfd,msg,strlen(msg),0,NULL,0);is not. Hint: read the book and/or read the recvfrom/sendto man pages.
listen and accept
system calls, while the UDP server described below does not.
1 /***********************************************************
2 * A simple UDP server program. It just reads messages and
3 * prints them out along with the identity of sending host.
4 ***********************************************************/
5 #include <sys/types.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <sys/socket.h>
9 #include <netinet/in.h>
10 #include <arpa/inet.h>
11 #include <netdb.h>
12
13 int main(int argc, char **argv)
14 {
15 /* Set up socket */
16 int sfd = socket(AF_INET,SOCK_DGRAM,0);
17 if (sfd == -1) { fprintf(stderr,"Socket not created!\n"); exit(1); }
18
19 /* Get current host's IP address. */
20 struct hostent *p;
21 p = gethostbyname(getenv("HOST"));
22 if (p == NULL) { fprintf(stderr,"Name not found!\n"); exit(2); }
23 unsigned int *ip = (unsigned int*)(p->h_addr_list[0]);
24
25 /* Set up address structure */
26 struct sockaddr_in mysa;
27 mysa.sin_family = AF_INET;
28 mysa.sin_addr.s_addr = *ip;
29 mysa.sin_port = htons(10000);
30
31 /* Bind socket to address */
32 if (bind(sfd,(struct sockaddr*)&mysa,sizeof(mysa)) < 0)
33 {
34 close(sfd);
35 fprintf(stderr,"bind failed!\n");
36 exit(3);
37 }
38
39 while(1)
40 {
41 /* Define buffer in which to recieve client's message. */
42 char msg[257] = {'\0'};
43
44 /* Set up structure for client's host+port and recieve datagram! */
45 struct sockaddr_in sourcesa = {0};
46 int ssize = sizeof(sourcesa);
47 int r = recvfrom(sfd,msg,256,0,(struct sockaddr*)&sourcesa,&ssize);
48
49 /* Print host and message. */
50 struct hostent *he= gethostbyaddr((char *)&sourcesa.sin_addr.s_addr,4,AF_INET);
51 printf("Got message from '%s' (IP %u)!\n",he->h_name,sourcesa.sin_addr.s_addr);
52 if (r == 0)
53 printf("-->%i-byte message!\n",r);
54 else
55 printf("-->%i-byte message: %s",r,msg);
56 }
57
58 fprintf(stderr,"Server shutting down!\n");
59 close(sfd);
60 return 0;
61 }