/* udp1.c: illustrate socket() and bind() syscalls */ #include #include #include #include #include #include #include #include /* ----------------------------------------------------------------- paddr: print the IP address in a standard decimal dotted format ----------------------------------------------------------------- */ void paddr(unsigned char *a) { printf("%d.%d.%d.%d\n", a[0], a[1], a[2], a[3]); } int main(int argc, char *argv[]) { int s; /* s = socket */ struct sockaddr_in in_addr; /* Internet address */ if (argc < 3) { printf("Usage: %s \n", argv[0]); printf(" Program creates a UDP socket and binds it to \n"); printf(" Use = 0 for INADDR_ANY...\n"); printf(" Use 'host W301' to find IP-address (2861340441) !!\n"); printf(" Also try bind to a different IP address \n"); exit(1); } /* --- Create a UDP socket --- */ s = socket(PF_INET, SOCK_DGRAM, 0); /* --- Set up socket end-point info for the bind() call --- */ in_addr.sin_family = AF_INET; /* Protocol domain */ in_addr.sin_addr.s_addr = htonl(atoi(argv[1])); /* IP address of socket */ in_addr.sin_port = htons(atoi(argv[2])); /* UDP port # of socket */ /* --- Here goes the binding... --- */ if (bind(s, (struct sockaddr *)&in_addr, sizeof(in_addr)) != 0) { printf("Error: bind to addr = %s, port = %s FAILED\n", argv[1], argv[2]); perror("Bind ?"); exit(1); } else { struct sockaddr_in sock_addr; int len; 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(" = "); paddr( (void*) &sock_addr.sin_addr ); printf(" port = %u\n", ntohs(sock_addr.sin_port)); } while(1); /* Keep the port, try use udp1 to bind again... */ }