Tuesday, July 30, 2013

Foray Into Socket Programming in C++

Had to go linuxy on this one, since the Windows stuff was wonky.  Works though.  Simple server.  Gotta start somewhere!

Line 15 creates the socket, line 20 binds it and gives it my specified properties (ports/IP to listen on), and line 25 makes it listen for connections.

Line 38 is in a loop which will accept a connection from a client. 

Line 43 basically turns the socket handle into a file, to make reading and writing to it super easy.  It'll echo back the IP of the client and then close the connection.

1:  #include <stdio.h>  
2:  #include <sys/socket.h>  
3:  #include <arpa/inet.h>  
4:  #include <unistd.h>  
5:    
6:  int main()  
7:  {  
8:       int sockethandle, bindedhandle, listeninghandle;  
9:       sockaddr_in server_info;  
10:         
11:       server_info.sin_family = AF_INET;  
12:       server_info.sin_addr.s_addr = htonl(INADDR_ANY);  
13:       server_info.sin_port = htons(7777);  
14:         
15:       if((sockethandle=socket(AF_INET, SOCK_STREAM, 0))<0)  
16:       {  
17:            fprintf(stderr, "Error creating Socket.\n");  
18:       }  
19:    
20:       bindedhandle = bind(sockethandle, (sockaddr *) &server_info, sizeof(server_info));  
21:         
22:       if(bindedhandle<0)  
23:            printf("bind error");  
24:         
25:       listeninghandle = listen(sockethandle, 3);  
26:         
27:       if(listeninghandle<0)  
28:            printf("listen error");  
29:         
30:       printf("listening on port: %d\n", ntohs(server_info.sin_port));  
31:       while(1)  
32:       {  
33:            int sessionsocket;  
34:            char *ipofclient;  
35:            struct sockaddr_in client_info;  
36:            unsigned int client_info_size = sizeof(client_info);  
37:              
38:            sessionsocket=accept(sockethandle, (sockaddr *) &client_info, &client_info_size);  
39:              
40:            ipofclient=inet_ntoa(client_info.sin_addr);  
41:            printf("client %s is connected\n\n", ipofclient);  
42:              
43:            FILE *read=fdopen(sessionsocket, "r");  
44:            FILE *write=fdopen(sessionsocket, "w");  
45:              
46:            fprintf(write, "GREETS, %s!\n", ipofclient);  
47:    
48:            fflush(write);  
49:            fclose(write);  
50:            fclose(read);  
51:            close(sessionsocket);  
52:       return 0;  
53:       }  
54:  }  


No comments:

Post a Comment