123456789101112131415161718192021222324252627282930313233343536373839404142 |
- // For socket programming
- #include <arpa/inet.h>
- #include <sys/socket.h>
- #include <stdlib.h>
- #include <netinet/in.h>
- #include <string.h>
- #include <errno.h>
- #include <unistd.h>
- #include <stdio.h>
- // Sets up a socket connected to the port passed as input - returns the socket FD on success and -1 on error.
- // Also prints the errno on error.
- int set_up_socket_connect(int port)
- {
- int sock = 0;
- if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
- {
- printf("\n Error in socket call - errno is %d \n", errno);
- return -1;
- }
- struct sockaddr_in serv_addr;
- memset(&serv_addr, '0', sizeof(serv_addr));
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_port = htons(port);
- // Convert IPv4 and IPv6 addresses from text to binary form
- if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
- {
- printf("\nError in inet_pton - errno is %d\n", errno);
- return -1;
- }
- if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
- {
- printf("\nError in connect - errno is %d \n", errno);
- return -1;
- }
- return sock;
- }
|