giuliomoro@24: /* Creates a datagram server. The port giuliomoro@24: number is passed as an argument. This giuliomoro@24: server runs forever */ giuliomoro@24: giuliomoro@24: #include giuliomoro@24: #include giuliomoro@24: #include giuliomoro@24: #include giuliomoro@24: #include giuliomoro@24: #include giuliomoro@24: #include giuliomoro@24: #include giuliomoro@24: giuliomoro@24: void error(const char *msg) giuliomoro@24: { giuliomoro@24: perror(msg); giuliomoro@24: exit(0); giuliomoro@24: } giuliomoro@24: giuliomoro@24: int main(int argc, char *argv[]) giuliomoro@24: { giuliomoro@24: int sock, length, n; giuliomoro@24: socklen_t fromlen; giuliomoro@24: struct sockaddr_in server; giuliomoro@24: struct sockaddr_in from; giuliomoro@24: char buf[1024]; giuliomoro@24: giuliomoro@24: if (argc < 2) { giuliomoro@24: fprintf(stderr, "ERROR, no port provided\n"); giuliomoro@24: exit(0); giuliomoro@24: } giuliomoro@24: giuliomoro@24: sock=socket(AF_INET, SOCK_DGRAM, 0); giuliomoro@24: if (sock < 0) error("Opening socket"); giuliomoro@24: length = sizeof(server); giuliomoro@24: bzero(&server,length); giuliomoro@24: server.sin_family=AF_INET; giuliomoro@24: server.sin_addr.s_addr=INADDR_ANY; giuliomoro@24: server.sin_port=htons(atoi(argv[1])); giuliomoro@24: if (bind(sock,(struct sockaddr *)&server,length)<0) giuliomoro@24: error("binding"); giuliomoro@24: fromlen = sizeof(struct sockaddr_in); giuliomoro@24: while (1) { giuliomoro@24: n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen); giuliomoro@24: if (n < 0) error("recvfrom"); giuliomoro@24: write(1,"Received a datagram: ",21); giuliomoro@24: write(1,buf,n); giuliomoro@24: n = sendto(sock,"Got your message\n",17, giuliomoro@24: 0,(struct sockaddr *)&from,fromlen); giuliomoro@24: if (n < 0) error("sendto"); giuliomoro@24: } giuliomoro@24: return 0; giuliomoro@24: } giuliomoro@24: