diff options
Diffstat (limited to 'bind.c')
-rw-r--r-- | bind.c | 43 |
1 files changed, 43 insertions, 0 deletions
@@ -0,0 +1,43 @@ +#include <sys/socket.h> +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <arpa/inet.h> +#include <unistd.h> + +static void fail(const char *err) { + perror(err); + exit(1); +} + +int main(int argc, char **argv) { + unsigned short int port; + int sockfd; + struct sockaddr_in addr; + struct in_addr sa; + + if (argc < 2) { + printf("Usage: %s port\n", argv[0]); + return -1; + } + port = atoi(argv[1]); + printf("Port: %hu\n", port); + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd < 0) fail("socket"); + + memset(&addr, 0, sizeof addr); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + sa.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_addr = sa; + printf("sockfd = %i\naddr = %p\nsizeof addr = %zi\n", sockfd, + (struct sockaddr *)&addr, sizeof addr); + if (bind(sockfd, (struct sockaddr *)&addr, sizeof addr) < 0) fail("bind"); + + if (listen(sockfd, 10) < 0) fail("listen"); + + if (close(sockfd) < 0) fail("close"); + printf("Success!\n"); + return 0; +} |