/* udp4-r.c: first communication program... - receiver: opens a UDP socket and receives on it... */ #include #include #include #include #include #include #include #define MAXSIZE 100 int main(int argc, char *argv[]) { int s; /* s = socket */ struct sockaddr_in in_addr; /* Structure used for bind() */ struct sockaddr_in sock_addr; /* Output structure from getsockname */ struct sockaddr_in src_addr; /* Used to receive (addr,port) of sender */ int src_addr_len; /* Length of src_addr */ int len; /* Length of result from getsockname */ char line[MAXSIZE]; if (argc < 3) { printf("Usage: %s IP-addr(in decimal...) port\n", argv[0]); printf(" - lab1a IP addr = 2861340526\n"); printf(" - lab1b IP addr = 2861340527\n"); exit(1); } /* --- Create a socket --- */ s = socket(PF_INET, SOCK_DGRAM, 0); /* --- Set up socket end-point info for binding --- */ in_addr.sin_family = AF_INET; /* Protocol family */ in_addr.sin_addr.s_addr = htonl(atoi(argv[1])); /* IP address */ in_addr.sin_port = htons(atoi(argv[2])); /* UDP port */ /* --- Here goes the binding... --- */ if (bind(s, (struct sockaddr *)&in_addr, sizeof(in_addr)) == -1) { perror("bind: error... reason was"); exit(1); } else { printf("OK: bind SUCCESS\n"); } /* -------------------------------------------------------- **** Print socket "name" (which is IP-address + Port#) -------------------------------------------------------- */ len = sizeof(sock_addr); getsockname(s, (struct sockaddr *) &sock_addr, &len); printf("Socket is bind to:\n"); printf(" addr = %u\n", ntohl(sock_addr.sin_addr.s_addr) ); printf(" port = %u\n", ntohs(sock_addr.sin_port) ); while(1) { src_addr_len = sizeof(src_addr); len = recvfrom(s, line, MAXSIZE, 0 /* flags */, (struct sockaddr *) &src_addr, &src_addr_len); printf("Msg from (%u,%u): `%s' (%u bytes)\n", ntohl(src_addr.sin_addr.s_addr), ntohs(src_addr.sin_port), line, len); } }