View Single Post
Old Mar 1st, 2008, 12:14 PM   #1
Soulstorm
Hobbyist Programmer
 
Soulstorm's Avatar
 
Join Date: Jan 2006
Location: Menidi, Athens, Greece
Posts: 243
Rep Power: 3 Soulstorm is on a distinguished road
Simple BSD Sockets Problem

I am diving into network connections, using the BSD sockets. My ultimate goal is to make a very basic IRC client, just to learn how to do network connections. My operating system is OS X, but I don't think that makes a difference, since I believe BSD Sockets exist in other platforms, too.

I am stuck.

I have created a command line tool in C and I have the following code:

c Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. #include <string.h>
  6. #include <netdb.h>
  7. #include <sys/types.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10.  
  11. #define PORT 6667 // the port client will be connecting to
  12.  
  13. #define MAXDATASIZE 1000 // max number of bytes we can get at once
  14.  
  15. int main(int argc, char *argv[])
  16. {
  17. int sockfd, numbytes;
  18. char buf[MAXDATASIZE];
  19. struct hostent *he;
  20. struct sockaddr_in their_addr; // connector's address information
  21.  
  22. he = gethostbyname("efnet.teleglobe.net");
  23. sockfd = socket(PF_INET, SOCK_STREAM, 0);
  24. if (sockfd < 0) {
  25. printf("error creating the socket\n");
  26. }
  27. their_addr.sin_family = AF_INET;
  28. their_addr.sin_port = htons(PORT);
  29. their_addr.sin_addr = *((struct in_addr *)he->h_addr);
  30. memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
  31.  
  32.  
  33. if (connect(sockfd, (struct sockaddr *)&their_addr,
  34. sizeof their_addr) == -1) {
  35. perror("connect\n");
  36. exit(1);
  37. }
  38. else
  39. printf("You got the connection to the server!\n");
  40. char p[] = "join #macfilez";
  41. send(sockfd, p, sizeof(p), 0);
  42.  
  43. recv(sockfd, buf, sizeof(buf), 0);
  44. buf[numbytes] = '\0';
  45. printf("Received: %s",buf);
  46. close(sockfd);
  47.  
  48. return 0;
  49. }
The server I put was a server running on IRC's EFNet network. I was supposed to receive a message, from the server, right? Not only this doesn't happen, my program also crashes without showing anything! (the debugger comes up with no explanation).

Any ideas why? Actually, I must have made a newbie mistake due to my ignorance. Please enlighten me.
__________________
Project::Soulstorm (personal homepage)

Last edited by Soulstorm; Mar 1st, 2008 at 12:27 PM.
Soulstorm is offline   Reply With Quote