/* udp2.c: illustrate bind() on INADDR_ANY IP-address - result: this will work on any machine without you needing to - know its IP address, and as long as the specified port is - avaliable (not used by a diff. process) */ #include #include #include #include #include #include #include void main(int argc, char *argv[]) { int s; /* s = socket */ struct sockaddr_in in_addr; /* Internet address */ if (argc < 2) { printf("Usage: %s \n", argv[0]); printf(" Program creates a UDP socket and binds it to \n", argv[0]); 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 domain */ in_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Use wildcard IP address */ in_addr.sin_port = htons(atoi(argv[1])); /* UDP port # of socket */ /* --- Here goes the binding... --- */ if (bind(s, (struct sockaddr *)&in_addr, sizeof(in_addr)) == -1) { printf("Error: bind to port = %s FAILED\n", argv[1]); } else { struct sockaddr_in sock_addr; int len; printf("OK: bind to port = %s SUCCESS\n", argv[1]); len = sizeof(sock_addr); getsockname(s, (struct sockaddr *) &sock_addr, &len); printf("**** Bind was successful....\n"); 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) ); } }