1 /* Creates a datagram server. The port
2 number is passed as an argument. This
8 #include <sys/socket.h>
9 #include <netinet/in.h>
14 void error(const char *msg
)
20 int main(int argc
, char *argv
[])
24 struct sockaddr_in server
;
25 struct sockaddr_in from
;
29 fprintf(stderr
, "ERROR, no port provided\n");
33 sock
=socket(AF_INET
, SOCK_DGRAM
, 0);
34 if (sock
< 0) error("Opening socket");
35 length
= sizeof(server
);
36 bzero(&server
,length
);
37 server
.sin_family
=AF_INET
;
38 server
.sin_addr
.s_addr
=INADDR_ANY
;
39 server
.sin_port
=htons(atoi(argv
[1]));
40 if (bind(sock
,(struct sockaddr
*)&server
,length
)<0)
42 fromlen
= sizeof(struct sockaddr_in
);
44 n
= recvfrom(sock
,buf
,1024,0,(struct sockaddr
*)&from
,&fromlen
);
45 if (n
< 0) error("recvfrom");
46 write(1,"Received a datagram: ",21);
48 n
= sendto(sock
,"Got your message\n",17,
49 0,(struct sockaddr
*)&from
,fromlen
);
50 if (n
< 0) error("sendto");