systemIpc.cpp 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // For socket programming
  2. #include <arpa/inet.h>
  3. #include <sys/socket.h>
  4. #include <stdlib.h>
  5. #include <netinet/in.h>
  6. #include <string.h>
  7. #include <errno.h>
  8. #include <unistd.h>
  9. #include <stdio.h>
  10. // Sets up a socket connected to the port passed as input - returns the socket FD on success and -1 on error.
  11. // Also prints the errno on error.
  12. int set_up_socket_connect(int port)
  13. {
  14. int sock = 0;
  15. if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  16. {
  17. printf("\n Error in socket call - errno is %d \n", errno);
  18. return -1;
  19. }
  20. struct sockaddr_in serv_addr;
  21. memset(&serv_addr, '0', sizeof(serv_addr));
  22. serv_addr.sin_family = AF_INET;
  23. serv_addr.sin_port = htons(port);
  24. // Convert IPv4 and IPv6 addresses from text to binary form
  25. if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
  26. {
  27. printf("\nError in inet_pton - errno is %d\n", errno);
  28. return -1;
  29. }
  30. if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
  31. {
  32. printf("\nError in connect - errno is %d \n", errno);
  33. return -1;
  34. }
  35. return sock;
  36. }